// ==UserScript==
// @name            Face Book Mafia Gift Acceptor
// @description     Will Accept all Mafia Wars and FaceBook Gift Request, friend invites, and can ignore EVERYTHING else.
// @namespace       MafiaWars
// @include         http://www.facebook.com/*
// @include         http://facebook.mafiawars.com/mwfb/*
// @exclude         http://apps.facebook.com/*
// @exclude         http://www.facebook.com/extern/*
// @exclude         http://www.facebook.com/connect/*
// @exclude         http://www.facebook.com/login.php*
// @version         0.10.16
// @contributor     Shrubber, Bubba123, Weckl, s1lv3rw0lf
// ==/UserScript==

//  Variables for Event trigger
var pass            = 0,
    change_count    = 0,
    notify_count    = 0,
    scheduled       = false;

//  Process Variables
var script_version  = "0.10.16";
var SUC_script_num  = 70459;

var strFBAutoAccept = 'FBAA-Header',
    strFBAALog      = 'FBAA-Log',
    strFBAASettings = 'FBAA-Settings',
    strFBAASetTabs  = 'FBAA-SettingTab',
    strFBAASetDivs  = 'FBAA-SettingDiv',
    strAutoOn       = 'FBAA-AutoOn',
    strAutoOff      = 'FBAA-AutoOff',
    strLogShow      = 'FBAA-LogShow',
    strLogHide      = 'FBAA-LogHide';

var strFrameId;

var bAutoRun        = false,
    bAutoRunHold    = false,
    bShowLog        = false;

var oLogDiv;

var aParams         = new Array();

var strGroups;

var local_xw_user_id, local_xw_sig, local_xw_time, xw_sig_valid;
var FB_user_id;

var iRequestCurrent     = 0,
    iWallCurrent        = 0,
    iRespectCurrent     = 0,
    iMW_XW_Timer        = 0,
    iFB_XW_Timer        = 0;
var iRequestNum;

var FV_accept_ignore    = 0;

var bInitialized = false;

var EventSpan, ActionWall, ActionRequest, ActionRespect;
var oRespectList, oWallList, oRequestList;



/****  Icons   ****/
var imgLogo = 'data:image/jpg;base64,'+
    '/9j/4AAQSkZJRgABAQEAAQABAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcG'+
    'BwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwM'+
    'DAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAoACgDASIA'+
    'AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA'+
    'AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3'+
    'ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm'+
    'p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA'+
    'AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx'+
    'BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK'+
    'U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3'+
    'uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0HxJY'+
    'X2qaPPHpt6LC+KsIZim9AxUgBh1xznI5BAODjaaGk+M7m58XvpWo6XcaRLNa/aLQyMksVyUYrMsc'+
    'isdwUNEw3BHKuxKDaca93aR6jYzW0jSrHcRtCxjco6qwwSrAgg4JwQQRXA+JPi9dfGzQ7nw5feBm'+
    '8EeKfDDi80nWdG06AMPskdxbPcGCFjJcRuUhc3E0FvEYnulO1JyT+KUoKSep+gczWttD0guu0k5B'+
    'PBrkbrxTqviW/wBYsdEspBFaSCzi1SbaLSG4Qt57HDb5hG2I9iKMyRSozxjDj1v4ufsJ6j8P/hB4'+
    'g1/TPifYpqGk6VNqKXNldXd6dRZA7bLaGUGB5JthSPZvxIwCJJt2N41p3xZgtrq0+F2gfDpLXQ9M'+
    'ZILnxDdQxtfwNGv2glpmdrq2ZmUQrBLChcJLJ5xaZxWrw0oJ8+gqVeNT4NfwOvt4DbWkcbzSTMig'+
    'NJIAGc9yQAACTzgAD0opTIQDnB9aK5TUxfiH+0d4E/ZX8A6J4t8W2h1u5m1a7s7rTLu4WO2ghWIy'+
    'Wr+TJaMk7yOjRmKOdyB5chkgDSrDsfAL9tHxb4x/Zo8a6rP4M0z4bp4nvtP0S2is4pF1DUrL7JdS'+
    'L5z/ACxiWYRKqR7Q7LJdOAwkLpV8R/GLxB8DtAvvEHhnwxqXjbU0tpLY6DZrI7alCQJZA6xncYo1'+
    'h81iVkUCIlo2A47D4e3Nj+19bWXgbxv4a8N/DfUvGdoz6LqGmXqam0WqxsksFvJcJBbr88H2kKI1'+
    'ZWcH5pW2B/Uw8/3a5Wk9vmcVWCV3JX87/oczN8DNb8A/HT4hfE+X9oT4c+JPDOrx+NL7w54S0jVp'+
    'H1yyvPENv5bKyeWsgMTRWm4y4WMW+7EOWBqfti/8FCtU+Hvijwj4l8S+AtD8YeE/Evhu3utc8RR2'+
    'ha/0stc3mnRttlV0e3ZtPM8bbdqvcyAbyVEnbaF+wX8U/iV8Vda+G2qeMPBsEPh+20+6125s5JHu'+
    'zYXst0kTCMAENKlnOwRggIMQLKHfZznxg/aMPwes9Uk+Ffwu0H4heGdEmt9L0VRfC2vNUjgSGJ7m'+
    'CEWsxujcXKz4VZEaeNwVEjSA1spVFpP3exCUJSXL71vlp6/iZ+mfEXwt8YfA3hzxh4Siks4fEsk8'+
    'txpcV6b+106FFCRNHN9kgQrKyNIdsjshkWMwptYoVan8VX3jzbreqWt3ZalqccdxcW10GFxaOUA8'+
    'mTc8jb0ACEtI7EoSXc5YleXVtKba0OqCskiXTdUudF1G3vLK6urG+tJVmhubeZopYHUghlZTkH9C'+
    'Mg5BIq+3iiPVpHXWdF8M6/FOyyXL3WntDdXDqVZWM1tJEysrKrKybWVgGBDAGiiiNSUfhYnBS1ZW'+
    'uvGmqazcXX9oaZ4SN1qcU1prXiC1s3g13xRaSEkW95KhVRyVE8keGuggVhEhkSSaPxpfabCI9Mt9'+
    'G0AqnkifR9PFpctFtC+WZCzkLgdI9mMnGKKKt4mo92JUYLoZMapbQIiIEVFCgDoABiiiisrmh//Z';
    
var imgCatagory = {
		0:	'data:image/gif;base64,'+
			'R0lGODlhEAAQAPcAAAAAAAAAMwAAZgAAmQAAzAAA/wArAAArMwArZgArmQArzAAr/wBVAABVMwBV'+
			'ZgBVmQBVzABV/wCAAACAMwCAZgCAmQCAzACA/wCqAACqMwCqZgCqmQCqzACq/wDVAADVMwDVZgDV'+
			'mQDVzADV/wD/AAD/MwD/ZgD/mQD/zAD//zMAADMAMzMAZjMAmTMAzDMA/zMrADMrMzMrZjMrmTMr'+
			'zDMr/zNVADNVMzNVZjNVmTNVzDNV/zOAADOAMzOAZjOAmTOAzDOA/zOqADOqMzOqZjOqmTOqzDOq'+
			'/zPVADPVMzPVZjPVmTPVzDPV/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYAmWYAzGYA/2Yr'+
			'AGYrM2YrZmYrmWYrzGYr/2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA/2aqAGaq'+
			'M2aqZmaqmWaqzGaq/2bVAGbVM2bVZmbVmWbVzGbV/2b/AGb/M2b/Zmb/mWb/zGb//5kAAJkAM5kA'+
			'ZpkAmZkAzJkA/5krAJkrM5krZpkrmZkrzJkr/5lVAJlVM5lVZplVmZlVzJlV/5mAAJmAM5mAZpmA'+
			'mZmAzJmA/5mqAJmqM5mqZpmqmZmqzJmq/5nVAJnVM5nVZpnVmZnVzJnV/5n/AJn/M5n/Zpn/mZn/'+
			'zJn//8wAAMwAM8wAZswAmcwAzMwA/8wrAMwrM8wrZswrmcwrzMwr/8xVAMxVM8xVZsxVmcxVzMxV'+
			'/8yAAMyAM8yAZsyAmcyAzMyA/8yqAMyqM8yqZsyqmcyqzMyq/8zVAMzVM8zVZszVmczVzMzV/8z/'+
			'AMz/M8z/Zsz/mcz/zMz///8AAP8AM/8AZv8Amf8AzP8A//8rAP8rM/8rZv8rmf8rzP8r//9VAP9V'+
			'M/9VZv9Vmf9VzP9V//+AAP+AM/+AZv+Amf+AzP+A//+qAP+qM/+qZv+qmf+qzP+q///VAP/VM//V'+
			'Zv/Vmf/VzP/V////AP//M///Zv//mf//zP///wAAAAAAAAAAAAAAACH5BAEAAPwALAAAAAAQABAA'+
			'AAiQAPcJHEiwoEFl9AqiMThQmZiBDxkOyxQmhkBlDCHGuLEPGrGM+5ShESNG2EeQAyPp0ody4DBd'+
			'61ruy6FmFzB2IDUBSZNmn6J18xgqy5FDBsZktICxLPggDQ4HAxXBLJgjTQ4EBaUGG6gJR1FN++hF'+
			'q7dPmLB5CUMSHZMp0yRJmdJkUqRoWLSBy1hijJb2rsCAADs=',
		1:	'data:image/gif;base64,'+
			'R0lGODlhEAAQAKIAAAAAAOvu9DtZmEVinm2EtGF5rP///wAAACH5BAEHAAAALAAAAAAQABAAAAM+'+
			'CLrcWiLKGYuiWN5cgjHRhnlfCGRCqZ2ZamJfDAqiFJD32846zNMs30QxIBiPhM9xQEQelUYmAIKS'+
			'WBzYRQIAOw==',
		2:	'data:image/gif;base64,'+
			'R0lGODlhEAAQAPUAAAAAAAYGBgkJCRERERcXFxsbGx4eHiQkJCoqKi4uLjIyMjQ0NDk5OT4+PkBA'+
			'QEdHR0pKSlBQUFdXV15eXmJiYmZmZmpqanNzc3R0dH9/f4CAgIWFhYuLi42NjZGRkZeXl5ubm56e'+
			'nqampqqqqqysrLa2trq6ur+/v8HBwcXFxcjIyM/Pz9PT09fX19ra2t/f3+Pj4+Xl5evr6/Hx8fT0'+
			'9Pn5+f39/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAAAAAAALAAAAAAQABAAAAbQQIOj'+
			'sVg4DAAAwcFYMByHgCM0In2QSs5oBIIIAAfSaoVaJBUklWqUSIZbLNclWRmvSoekoQR7xUwFAyIv'+
			'Li4nCHonMjGLEhAtMTAxKmYABik0MzU1IBuaMzMtDW4tNjUnNS4qNCo1NjIPSQguphYsNjYuGDKv'+
			'DkkLMKYZJbgmFzOvowAOMcIduB4XNDYxygzNNhcSMzQVFdOwSQm0NhYHKy4KFK4yELKl5QIiJQIT'+
			'0zG+AAzBNhgAFv4sTKMRAUADDB88fODQgEHDDSEianAQBAA7',
		3:	'data:image/gif;base64,'+
			'R0lGODlhEAAQAPMKAAAAABlLGShjKH5+fo5DAMheAESMRHq0eviwFfrybwAAAAAAAAAAAAAAAAAA'+
			'AAAAACH5BAEAAAoALAAAAAAQABAAAARZUMmpCko0z3GRzpyVeJ80WGIpAYRIlgB6KUYm3KxrBDUF'+
			'BAFZIvDhBVqXgsFwoPCWBISFsGNKeADAEoXlXQWKgbb1VPyuE62BagADwBl12fwRV4mq8A9PiQAA'+
			'Ow==',
		4:	'data:image/gif;base64,'+
			'R0lGODlhEAAQAPcAAAAAAAAAMwAAZgAAmQAAzAAA/wArAAArMwArZgArmQArzAAr/wBVAABVMwBV'+
			'ZgBVmQBVzABV/wCAAACAMwCAZgCAmQCAzACA/wCqAACqMwCqZgCqmQCqzACq/wDVAADVMwDVZgDV'+
			'mQDVzADV/wD/AAD/MwD/ZgD/mQD/zAD//zMAADMAMzMAZjMAmTMAzDMA/zMrADMrMzMrZjMrmTMr'+
			'zDMr/zNVADNVMzNVZjNVmTNVzDNV/zOAADOAMzOAZjOAmTOAzDOA/zOqADOqMzOqZjOqmTOqzDOq'+
			'/zPVADPVMzPVZjPVmTPVzDPV/zP/ADP/MzP/ZjP/mTP/zDP//2YAAGYAM2YAZmYAmWYAzGYA/2Yr'+
			'AGYrM2YrZmYrmWYrzGYr/2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA/2aqAGaq'+
			'M2aqZmaqmWaqzGaq/2bVAGbVM2bVZmbVmWbVzGbV/2b/AGb/M2b/Zmb/mWb/zGb//5kAAJkAM5kA'+
			'ZpkAmZkAzJkA/5krAJkrM5krZpkrmZkrzJkr/5lVAJlVM5lVZplVmZlVzJlV/5mAAJmAM5mAZpmA'+
			'mZmAzJmA/5mqAJmqM5mqZpmqmZmqzJmq/5nVAJnVM5nVZpnVmZnVzJnV/5n/AJn/M5n/Zpn/mZn/'+
			'zJn//8wAAMwAM8wAZswAmcwAzMwA/8wrAMwrM8wrZswrmcwrzMwr/8xVAMxVM8xVZsxVmcxVzMxV'+
			'/8yAAMyAM8yAZsyAmcyAzMyA/8yqAMyqM8yqZsyqmcyqzMyq/8zVAMzVM8zVZszVmczVzMzV/8z/'+
			'AMz/M8z/Zsz/mcz/zMz///8AAP8AM/8AZv8Amf8AzP8A//8rAP8rM/8rZv8rmf8rzP8r//9VAP9V'+
			'M/9VZv9Vmf9VzP9V//+AAP+AM/+AZv+Amf+AzP+A//+qAP+qM/+qZv+qmf+qzP+q///VAP/VM//V'+
			'Zv/Vmf/VzP/V////AP//M///Zv//mf//zP///wAAAAAAAAAAAAAAACH5BAEAAPwALAAAAAAQABAA'+
			'AAi6APcJHLhsU6hlAxMOhBMkTqg4cdRsUrhvGRyHm+Bo2nQnYrSB0STGAZUw1EU1A+Nw1LQv2qaJ'+
			'+14eYblPzcNN0TTFOaJsHyiVOipihBgnCMtoEEPpgKZzU5yLRoWugRhk2KYjcJzGCboPyNQgOoAQ'+
			'U7YmSMOiToMAWQsWWteiatRm9Go2SA6Bmo6s0QtHoFmvOtIMVBNn75qCQOriSBgtB8QjiQvrWDxQ'+
			'H94cOtYA0eFgEsWE0IaNpRgQADs='
		}
    
/****	Link List Header	****/
List = function(_cycle) {

	var Self = this;

	this.First	= null;
	this.Last	= null;
	
	// empty list
	this.Erase	= function() {
		var pointer = this.First;
		var hold;
		while (pointer != null) {
			hold = pointer.Next;
			pointer = null;
			pointer = hold;
		}
		this.First	= null;
		this.Last	= null;
	};

	//start to action the data elements in the list
	this.Run	= function() {
		var oHold;
		if (this.First == null) {
			// load List
			_cycle();
		} else {
			// remove the top element from the list and action it
			oHold = this.First;
			this.First = oHold.Next;
			oHold.Process();
		};
	};

	// add to the bottom of the list
	this.Append	= function(_data) {
		if (this.First == null) {
			this.First 	= _data;
			this.Last  	= _data;
		} else {
			this.Last.Next	= _data;
			this.Last	= _data;
		};
	};
	
	// add to the top of the list
	this.Insert	= function(_data) {
		if (this.First == null) {
			this.First 	= _data;
			this.Last  	= _data;
		} else {
			_data.Next	= this.First;
			this.First	= _data;
		};
	};
}
/****	End of Link List Header	****/   

/****  Engine for Processing Wall posting, Requests, and Respect    ****/

// regex search items
var strConfirmBoxes     =   '//div[@class="confirm_boxes"]',
    strFormInputs       =   './form',
    strFormInputs1      =   './/form',
    strEvent            =   './input',
    strInput            =   './/input',
    strReqTypes         =   '//span[contains(@id,"_label")]',
    strWarBetray        =   '//span[contains(text(),"Betray")]/parent::*',
    strWarAttackBetray  =   '//div[contains(@style,"position: absolute")]/a',
    strWarAttack        =   '//div[contains(@style,"float: left")]/div[contains(@style,"position: absolute")]/a';

var strBase             =   'http://www.facebook.com/ajax/reqs.php?__a=1',
    strAccept           =   '&actions[accept]=Confirm',
    strReject           =   '&actions[reject]=Ignore';

// regex for Wall data
var Wall_Data = {
    // Mafia Wars
    '10979261223': {
        MW_WarHelp:         {testURL:   /\?next_controller=war&next_action=view/i,
                             testIMG:   /\B|./i},
        MW_Burner:          {testURL:   /\?next_controller=robbing&next_action=call_for_help_get_phone/i,
                             testIMG:   /\B|./i},
        MW_FriendofFriend:  {testURL:   /\?next_controller=job&next_action=give_help|\?next_controller=job&xw_action=give_help|\?next_controller=story&next_action=give_help_moscow_social|\?next_controller=story&next_action=give_help_social/i,
                             testIMG:   /socialagain/i},
        MW_NeedHelp:        {testURL:   /\?next_controller=job&next_action=give_help|\?next_controller=job&xw_action=give_help|\?next_controller=story&next_action=give_help_moscow_social|\?next_controller=story&next_action=give_help_social/i,
                             testIMG:   /\B|./i},
        MW_Achievement:     {testURL:   /track.php\?sendkey=.{0,}&next_action=ach_celeb/i,
                             testIMG:   /\B|./i},
        MW_BossBonus:       {testURL:   /\?next_controller=story&next_action=claim_boss_bonus/i,
                             testIMG:   /\B|./i},
        MW_IcedBonus:       {testURL:   /\?next_controller=index&next_action=iced_boost_claim/i,
                             testIMG:   /\B|./i},
        MW_LevelUp:         {testURL:   /\?next_controller=index&next_action=levelup_boost_claim/i,
                             testIMG:   /\B|./i},
        MW_HolidayBonus:    {testURL:   /\?next_controller=index&next_action=holiday_feed_reward/i,
                             testIMG:   /\B|./i},
        MW_SupplyParts:     {testURL:   /\?next_controller=propertyV2&next_action=cs_help_item|\?next_controller=propertyV2&next_action=wd_help_item/i,
                             testIMG:   /\B|./i},
        MW_NextTarget:      {testURL:   /\?next_controller=fight&next_action=social_attack/i,
                             testIMG:   /\B|./i},
        MW_Bounty:          {testURL:   /\?next_controller=hitlist&next_action=feed_hit/i,
                             testIMG:   /\B|./i},
        MW_LaunderMoney:    {testURL:   /\?next_controller=launder&next_action=give_help/i,
                             testIMG:   /\B|./i},
        MW_ChopShop:        {testURL:   /\?next_controller=propertyV2&next_action=cs_help_final.{0,}building_type%22%3A%2211%22%7D/i,
                             testIMG:   /\B|./i},
        MW_WeaponsDepot:    {testURL:   /\?next_controller=propertyV2&next_action=cs_help_final.{0,}building_type%22%3A%2212%22%7D/i,
                             testIMG:   /\B|./i},
        MW_Stash:           {testURL:   /\?next_controller=job&next_action=collect_loot|\?next_controller=fight&next_action=collect_fight_loot/i,
                             testIMG:   /\B|./i},
        MW_Robbing:         {testURL:   /\?next_controller=robbing&next_action=mastery_bonus/i,
                             testIMG:   /\B|./i}
        },
    // FarmVille
    '102452128776': {
        FV_BarnRaising:    {testURL:   /creative&cat=storage&subcat=friendHelp/i,
                         testIMG:   /\B|./i},
        FV_LendaHand:      {testURL:   /creative&cat=Feed_share_stable_needmaterials|creative&cat=share_nursery_askformore/i,
                         testIMG:   /\B|./i},
        FV_HelpaStallion:  {testURL:   /creative&cat=feed_stallion_overnight/i,
                         testIMG:   /\B|./i},
        FV_HatchanEgg:     {testURL:   /creative&cat=chickencoop/i,
                         testIMG:   /assets%2Fdecorations%2Fdeco_egg/i},
        FV_SendDogTreats:  {testURL:   /creative&cat=pet_treats_askformore/i,
                         testIMG:   /\B|./i},
        FV_AdoptanAminal:  {testURL:   /track.php?creative&cat=lonely_cow|creative&cat=Feed_share_nursery_adult|creative&cat=share_nursery_complete/i,
                         testIMG:   /\B|./i},
        FV_Collectable:    {testURL:   /creative&cat=collections/i,
                         testIMG:   /\B|./i},
        FV_Bonus:          {testURL:   /track.php?creative&cat=Achievements|creative&cat=chickencoop&subcat=self_no_egg|creative&cat=crop_mastery|creative&cat=feedChickens|creative&cat=feed_mission_MVP/i,
                         testIMG:   /\B|./i},
        FV_GetaBushel:     {testURL:   /creative&cat=feed_farmers_market_bushel_shared|creative&cat=feed_farmers_market_shopped|creative&cat=feed_farmers_market_stall_open|creative&cat=feed_farmers_market_stall_full/i,
                         testIMG:   /\B|./i},
        FV_Flower:         {testURL:   /creative&cat=flowers/i,
                         testIMG:   /\B|./i},
        FV_FarmHelp:       {testURL:   /creative&cat=Feed_share_stable_consumable&/i,
                         testIMG:   /\B|./i},
        FV_Fuel:           {testURL:   /creative&cat=fuel&subcat=friendHelp/i,
                         testIMG:   /\B|./i},
        FV_Matriels:       {testURL:   /creative&cat=feed_tuscan_wedding|creative&cat=feed_share_stable_halfway|creative&cat=feed_share_stable_expansion|creative&cat=share_nursery_materialcomplete/i,
                         testIMG:   /\B|./i}
        }
    }

// phrase key data for examining wall results, by language
var aStrLookUp = {
	1:  {   de_DE:'<span class="good">Gewonnen</span><br>',
            en_US:'<span class="good">Won</span><br>',
            es_ES:'<span class="good">Ganadas</span><br>',
            es_MX:'<span class="good">Ganadas</span><br>',
            fr_FR:'<span class="good">Vainqueur</span><br>',
            id_ID:'<span class="good">Menang</span><br>'},
	2:  {   de_DE:'Sie haben bereits in diesem Krieg teilgenommen',
            en_US:'You have already participated in this war',
            es_ES:'Ya has participado en esta guerra',
            es_MX:'Ya has participado en esta guerra',
            fr_FR:'Tu as dÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â©jÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â  participÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â© ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â  cette guerre',
            id_ID:'Anda telah berpartisipasi dalam perang ini'},
	3:  {   de_DE:'Dieser Krieg ist schon vorbei',
            en_US:'This war is over',
            es_ES:'Ya has participado en esta guerra',
            es_MX:'Ya has participado en esta guerra',
            fr_FR:'Cette guerre est dÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â©jÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â  terminÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â©e',
            id_ID:'Perang ini telah berakhir'},
	4:  {   de_DE:'<span>Krieg endet in:',
            en_US:'<span>War Ends in:',
            es_ES:'<span>La guerra termina en:',
            es_MX:'<span>La guerra termina en:',
            fr_FR:'<span>La guerre termine dans:',
            id_ID:'<span>Perang Berakhir dalam:'},
	5:  {   de_DE:'Sie <span class="good">haben</span> den Kampf GEWONNEN',
            en_US:'You <span class="good">WON</span> the fight',
            es_ES:'Has <span class="good">GANADO</span> la pelea',
            es_MX:'Has <span class="good">GANADO</span> la pelea',
            fr_FR:'Tu as <span class="good">WON</span> le combat',
            id_ID:'Anda <span class="good">WON</span> perkelahian ini'},
	6:  {   de_DE:'Sie <span class="bad">haben</span> den Kampf VERLOREN',
            en_US:'You <span class="bad">LOST</span> the fight',
            es_ES:'Has <span class="good">GANADO</span> la pelea',
            es_MX:'Has <span class="good">GANADO</span> la pelea',
            fr_FR:'Tu as <span class="bad">LOST</span> le combat',
            id_ID:'Anda <span class="bad">LOST</span> perkelahian ini'},
            
    9:  {   de_DE:"Dieses Geschenk ist abgelaufen! Achten Sie auf Ihre Geschenke sofort akzeptieren",
            en_US:"This gift has expired! Make sure to accept your gifts right away",
            es_ES:"Este regalo ha expirado! AsegÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Âºrese de aceptar sus regalos de inmediato",
            es_MX:"Este regalo ha expirado! AsegÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Âºrese de aceptar sus regalos de inmediato",
            fr_FR:"Ce don a expirÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â©! Assurez-vous d'accepter vos dons dÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¨s maintenant",
            id_ID:"Karunia ini telah berakhir! Pastikan untuk menerima hadiah Anda segera"},
    10: {   de_DE:"Ihr Freund hat Sie mehr als 1 freies Geschenk an einem Tag gesendet",
            en_US:"Your friend has sent you more than 1 free gift in a day",
            es_ES:"Tu amigo ha enviado mÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¡s de 1 regalo libre en un dÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â­a",
            es_MX:"Tu amigo ha enviado mÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¡s de 1 regalo libre en un dÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â­a",
            fr_FR:"Votre ami vous a envoyÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â© cadeau que vous plus de 1 gratuit par jour",
            id_ID:"Teman Anda telah mengirimkan hadiah Anda lebih dari 1 bebas dalam sehari"}
            
}

/****  Start MW Respect/CrimeSpree code ****/

// Respect gift
function RespectItem(){
	this.Next		=	null;
	this.Action		=	'';
	this.Process	=	function() {
		
		function NextRequest(_delay1, _delay2) {
	        if (Self.Next != null) {
                 iRespectCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRespect);}, getRandRange(_delay1*750,_delay1*1250));
            } else {
                LogPush('<strong>Finished processing crime spree gifts.  Checking again in '+ _delay2 +' minutes.</strong>');
                iRespectCurrent = setTimeout(function (e)  { EventSpan.dispatchEvent(ActionRespect);}, getRandRange(_delay2*50000,_delay2*70000));
            }
            if  (iRespectCurrent < iHoldEvent) {
	            // The browser has reset.  Cancel runaway jobs;
	            clearTimeout(iRespectCurrent);
            }
            
		}

	    function doStep1(_myUrl, _myParms) {
			var iCurrentJob, iWatchDog;
	
	        GM_log('doStep1');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doStep1(_myUrl,_myParms);
	            } else {
	                NextRequest(aParams[5],aParams[6])
	            }
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	            method: 'GET',
	            url:  _myUrl,
	            headers: {
	                'Host':            'facebook.mafiawars.com',
	                'User-agent':       navigator.userAgent,
	                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                'Accept-Language': 'en-us,en;q=0.5',
	                'Accept-Encoding': 'gzip,deflate',
	                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl;
	                    var strTemp;
	                    var strDetails;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        NextRequest(aParams[5],aParams[6])
	                    } else {
	
	                        strTemp     = _responseDetails.responseText;
	                        i1          = strTemp.indexOf('<td class="message_body">');
	                        i2          = strTemp.indexOf('<script',i1);
	
	                        strDetails  = strTemp.slice(i1,i2);
	
	                        LogPush('<strong>Accepting Crime Spree Gift</strong><br><table>'+strDetails+'</table>');
	                        NextRequest(aParams[5],aParams[6]);
	                    }
	
	                } catch(err) {
	                    GM_log('Error: Request DoStep 1 - '+err.message);
	                    NextRequest(aParams[5],aParams[6]);
	                } finally {
	                    i1          = null;
	                    i2          = null;
	                    myUrl       = null;
	                    strTemp     = null;
	                    strDetails  = null;                    
					}
	
	            }
	        });
	
	    }
	
	    try {
	        var myUrl, myParms;
	        var iErrorCount;
	        var iHoldEvent;
	        var Self;
	       
	        Self = this;
	
	        // stop processing if autorun turned off
	        if (bAutoRun) {
		        
		        iHoldEvent = iRespectCurrent;
		        
		        //stop the this cycle is mafia wars xw_sig is invalid
		        if (xw_sig_valid == false) {
		            GM_log('aborting Respect cycle.  XW_SIG is invalid');
		            // requeue the timed jobs for and hope xw_sig get renewed
		            LogPush('<strong>XW_Sig is invalid.  Aborting Crime Spree processing.  Checking again in '+aParams[6]+' minutes.</strong>');
		            iRespectCurrent = setTimeout(function (e) { oRespectList.erase(); EventSpan.dispatchEvent(ActionRespect);}, getRandRange(aParams[6]*50000,aParams[6]*70000));
		            if (iRespectCurrent < iHoldEvent) {
			            // The browser has reset.  Cancel runaway jobs;
			            clearTimeout(iRespectCurrent);
			        }
		            
		        } else {
		            iErrorCount = 0;
		
		            GM_log('accept Respect');
		
		            local_xw_sig = GM_getValue('local_xw_sig');
		            local_xw_user_id = GM_getValue('local_xw_user_id');
		
		            myUrl    = this.Action;
		            myUrl   += '&skip_req_frame=1'
		            myUrl   += '&sf_xw_sig=' 		+ local_xw_sig;
		            myUrl   += '&sf_xw_user_id='	+ local_xw_user_id;
		            
		            myParms	 = '';
		
		            doStep1(myUrl, myParms);
	            }
        	} else {
	            GM_log('Some one turned the swith off');
            }
	    } catch(err) {
	        GM_log('Error: Request Main - '+err.message);
	        NextRequest(aParams[5],aParams[6]);
	    } finally {
            myUrl       = undefined;
            myParms		= undefined;
		}
	};
};

/****  End MW Respect/CrimeSpree code ****/

/****  Start Wall Notification code ****/

// Process Wall Item

function WallItem(){
	this.Next		=	null;
	this.Action		=	'';
	this.AppId		=	'';
	this.Type		= 	'';
	this.Process	=	function() {
		
		function NextRequest(_delay1, _delay2) {
	        if (Self.Next != null) {
                iWallCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);}, getRandRange(_delay1*750,_delay1*1250));
            } else {
                iWallCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);}, getRandRange(_delay2*750,_delay2*1250));
            }
            if (iWallCurrent < iHoldEvent) {
	            // The browser has reset.  Cancel runaway jobs;
	            clearTimeout(iWallCurrent);
            }
		}
		
		// Mafia Wars Wall Code
	    
		function doMWStep1(_myUrl, _myParms) {
	        var iCurrentJob, iWatchDog;
	        GM_log('doMWStep1');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doMWStep1(_myUrl,_myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	            method: 'GET',
	            url:  _myUrl,
	            headers: {
	                'Host':            'apps.facebook.com',
	                'User-agent':       navigator.userAgent,
	                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                'Accept-Language': 'en-us,en;q=0.5',
	                'Accept-Encoding': 'gzip,deflate',
	                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl, myUrl2;
	                    var strTemp;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 1');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
	                        strTemp =   _responseDetails.responseText;
	                        i1 = strTemp.indexOf('window.location.replace(')+25;
	                        i2 = strTemp.indexOf(');<',i1);
	                        myUrl = eval("'"+strTemp.slice(i1,i2)+"'");
	                        doMWStep2(myUrl,'');
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 1 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                } 
	
	            }
	        });
	
	    }
	
	    function doMWStep2(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doMWStep2');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doMWStep2(_myUrl, _myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'GET',
	             url:  _myUrl,
	             headers: {
	                 'Host':            'apps.facebook.com',
	                 'User-agent':       navigator.userAgent,
	                 'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                 'Accept-Language': 'en-us,en;q=0.5',
	                 'Accept-Encoding': 'gzip,deflate',
	                 'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl;
	                    var strTemp;
	                    var strDetails;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 2');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
	                        strTemp =   _responseDetails.responseText;
	                        i1 = strTemp.indexOf('<iframe src="')+13;
	                        i2 = strTemp.indexOf('"',i1);
	                        myUrl = strTemp.slice(i1,i2);
	                        myUrl = myUrl.replace(/&amp;/g,'&');
	                        myUrl = decodeStrings(myUrl);
	                        //see if we still need this later
	                        myUrl = myUrl.replace(/%22/g,'"');
	                        doMWStep3(myUrl,'');
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 2 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                } 
	            }
	        });
	
	    }
	
	    function doMWStep3(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doMWStep3');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doMWStep3(_myUrl, _myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'HEAD',
	             url:  _myUrl,
	             headers: {
	                 'Host':            'facebook.mafiawars.com',
	                 'User-agent':       navigator.userAgent,
	                 'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                 'Accept-Language': 'en-us,en;q=0.5',
	                 'Accept-Encoding': 'gzip,deflate',
	                 'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, i3, myUrl, myParms;
	                    var strTemp;
	                    var strWarMessage, strWarName, strWarNotice;
	                    var strNotice;
	                    var strLang;
	                    var oDiv, oSnapShot;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 3');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
		                    // get webdata
							strTemp =   _responseDetails.responseText;
	                       
							// check language used
	                        strLang = checkLanguage(strTemp);
	                        
	                        if (Self.Type == 'MW_WarHelp') {
		                        
		                        //look for who won
		                        strWarName = '';
                                i1 = strTemp.indexOf(aStrLookUp[1][strLang]);
                                if (i1!=-1) {
                                    i1 += 33
                                    i2 = strTemp.indexOf('<br>',i1);
                                    strWarName = strTemp.slice(i1,i2);
                                    strWarName = strWarName.replace(/<script(.|\s)*?\/script>/g, '');
	                                strWarName = strWarName.replace(/color: rgb\(255, 255, 255\)/g, '');
	                                strWarName = strWarName.replace(/color: #fff/g, '');
                                }
                                GM_log('strWarName = '+strWarName);

                                //Look for Message
                                strWarMessage	= '';
                                strWarNotice	= '';
                                i1 = strTemp.indexOf('<td class="message_body">');
                                if (i1 !=-1) {
                                    i2 = strTemp.indexOf('</td>',i1);
                                    strWarMessage = strTemp.slice(i1+25,i2);
                                    // remove any javascript to be safe
                                    strWarMessage = strWarMessage.replace(/<script(.|\s)*?\/script>/g, '');
	                                strWarMessage = strWarMessage.replace(/color: rgb\(255, 255, 255\)/g, '');
	                                strWarMessage = strWarMessage.replace(/color: #fff/g, '');	                                    
                                    GM_log('strWarMessage = '+strWarMessage);

                                    i1 = strWarMessage.indexOf('<div style="margin');
                                    if (i1 == -1) {
                                        strWarNotice = strWarMessage.slice(0,i2);
                                    } else {
		                                i1 = strWarMessage.indexOf('">',i1)+2;
                                        i2 = strWarMessage.indexOf('</div>',i1);
                                        strWarNotice = strWarMessage.slice(i1,i2);
                                        i2 = strWarNotice.indexOf('<a href');
                                        if (i2!=-1) strWarNotice = strWarNotice.slice(0,i2);
                                    }
                                    // remove any javascript to be safe
                                    strWarNotice = strWarNotice.replace(/<script(.|\s)*?\/script>/g, '');
	                                strWarNotice = strWarNotice.replace(/color: rgb\(255, 255, 255\)/g, '');
	                                strWarNotice = strWarNotice.replace(/color: #fff/g, '');
	                                GM_log('strWarNotice = '+strWarNotice);
                                }
                                
   		                        if (strTemp.indexOf(aStrLookUp[2][strLang])!=-1) {
			                        //exit as you cannot participate in this war
			                        GM('You have already participated in this war');
			                        strNotice = aStrLookUp[2][strLang]
			                        LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                NextRequest(aParams[2],aParams[3]);
	
	                        	} else if (strTemp.indexOf(aStrLookUp[3][strLang])!=-1) {
	                                // this war is over
	                                GM_log('War is over');
	                                strNotice = aStrLookUp[3][strLang]+'. '+strWarName+' has won'
	                                LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                NextRequest(aParams[2],aParams[3]);
                                } else {
	                                //Isolate the part of the web page that has all the attack buttons on it
	                                i1 = strTemp.indexOf(aStrLookUp[4][strLang]);
	                                i2 = strTemp.indexOf('<div class="title">',i1);
	
	                                // This should contain all the attack buttons
	                                oDiv = document.createElement('div');
	                                oDiv.innerHTML = '<center>'+strTemp.slice(i1,i2);

	                                //Look to see if we are being asked to betray
	                                oSnapShot = getSnapshot(strWarBetray,oDiv);
	
	                                GM_log('Betray = '+oSnapShot.snapshotLength);
	                                GM_log('aParams[212] = '+aParams[212]);
	                                
	                                if (oSnapShot.snapshotLength >0) {
		                                if (aParams[212]==false) {
			                                // not allowed to betray
		                                    GM_Log('War ignored.  Betray present');
		                                    strNotice = 'Found War. Ignoring Betray Present';
		
		                                    LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
		                                    NextRequest(aParams[2],aParams[3]);
		                                } else {
			                                // pick someone to betray
		                                    GM_log('Selecting Person to Betray');
		                                    
		                                    strNotice = 'Found War. Selecting Person to Betray';
		                                    if (strWarNotice != '') strNotice	+= '<br>'+strWarNotice;
		
		                                    myUrl    =  oSnapShot.snapshotItem(getRandRange(0,1)).href
		                                    myUrl   +=  '&xw_client_id=8';
		
		                                    myParms = 'ajax=1&liteload=1'
		                                    myParms += '&sf_xw_sig=' + local_xw_sig;
		                                    myParms += '&sf_xw_user_id=' + local_xw_user_id;
		
		                                    doWarStep1(myUrl, myParms, strNotice);
		                                }
	                                } else {
		                                // War with No Betray
		                                
		                                // Select who to fight, right side or Both
		                                if (aParams[212]==true)
	                                        oSnapShot = getSnapshot(strWarAttackBetray,oDiv)
	                                    else
	                                        oSnapShot = getSnapshot(strWarAttack,oDiv);
	                                        
	                                    GM_log('Attack Buttons = '+oSnapShot.snapshotLength);
	                                    if (oSnapShot.snapshotLength == 0) {
		                                    //no one to attack
	                                        GM_log('no one to Attack');
	                                        
	                                        strNotice	= 'War is over.  No one to attack';
	                                        if (strWarNotice != '') strNotice	+= '<br>'+strWarNotice;
	
	                                        GM_log('War Error No Attack = '+oDiv.innerHTML);
	                                        
	                                        LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                        NextRequest(aParams[2],aParams[3]);
	                                    } else {
		                                    // attemp to attack
   	                                        GM_log('Attemp to attack');

	                                        strNotice = 'Found War. Found '+oSnapShot.snapshotLength+' Person/People to attack';
	                                        if (strWarNotice != '')	strNotice	+= '<br>'+strWarNotice;
	                                        
	                                        // look for local_xw_sig
	                                        local_xw_sig = GM_getValue('local_xw_sig');
	                                        local_xw_user_id = GM_getValue('local_xw_user_id');
	
	                                        myUrl    =  oSnapShot.snapshotItem(getRandRange(0,(oSnapShot.snapshotLength-1))).href
	                                        myUrl   +=  '&xw_client_id=8';
	
	                                        myParms = 'ajax=1&liteload=1'
	                                        myParms += '&sf_xw_sig=' + local_xw_sig;
	                                        myParms += '&sf_xw_user_id=' + local_xw_user_id;
	                                       
	                                        doWarStep1(myUrl, myParms, strNotice);
	                                    }
	                                }
                                }
	                        } else {
		                        // simple request (ie not a war)
	                            i1 = strTemp.indexOf('<td class="message_body">');
	                            
	                            if (i1 == -1) {
	                                strNotice = 'Error processing wall notification.  Cannot find results on page';
	                                GM_log(strNotice);
	                                LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                NextRequest(aParams[2],aParams[3]);
	                            } else {
		                            i2 = strTemp.indexOf('</td>',i1);
		                            strNotice = strTemp.slice(i1+25,i2);

		                            //GM_log('strNotice = '+strNotice);
		                            // look for button used to accept wall notification
	                                i1 = strNotice.indexOf('><a href="');
	                                if (i1 == -1) {
		                                //Remove and scripts and white text colour
		                                strNotice = strNotice.replace(/<script(.|\s)*?\/script>/g, '');
	                                    strNotice = strNotice.replace(/color: rgb\(255, 255, 255\)/g, '');
	                                    strNotice = strNotice.replace(/color: #fff/g, '');
	
	                                    LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                    NextRequest(aParams[2],aParams[3]);
	                                } else {
		                                i2 = strNotice.indexOf('"',i1+10);
	                                    // look for button to accept the job, gift, etc
	                                    
	                                    local_xw_sig = GM_getValue('local_xw_sig');
	                                    local_xw_user_id = GM_getValue('local_xw_user_id');
	
		                                myUrl =  strNotice.slice(i1+10,i2) + '&xw_client_id=8';
	                                    myUrl.replace(/\s/g, '%20');
	                                    
	                                    myParms  =  'ajax=1&liteload=1'
	                                    myParms +=  '&sf_xw_user_id='+local_xw_user_id;
	                                    myParms +=  '&sf_xw_sig='+local_xw_sig;
	                                    
	                                    //GM_log('myUrl = '+myUrl);
	                                    //GM_log('myParms = '+myParms);
	                                    
	                                    doMWStep4(myUrl,myParms);
	                                }
                            	}
	                        }
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 3 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                } 
	            }
	        });
	    }
	
	    function doMWStep4(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doMWStep4');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	
	            if (iErrorCount <3) {
	                doMWStep4(_myUrl,_myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	            method: 'POST',
	            url:  _myUrl,
	            data: _myParms,
	            headers: {
	                'Host':            'facebook.mafiawars.com',
	                'User-agent':       navigator.userAgent,
	                'Accept':          '*/*',
	                'Accept-Language': 'en-us,en;q=0.5',
	                'Accept-Encoding': 'gzip,deflate',
	                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                'Content-Type':    'application/x-www-form-urlencoded; charset=UTF-8',
	                'X-Requested-With':'XMLHttpRequest'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2;
	                    var strTemp;
	                    var strNotice;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 1');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
	
	                        strTemp =   _responseDetails.responseText;
	                        //GM_log("strTemp = "+strTemp);
	
	                        if (strTemp.indexOf('<div class="ach_celeb_message">')!=-1) {
	                            i1 = strTemp.indexOf('<div class="ach_celeb_message">');
	                            i2 = strTemp.indexOf('<div class="ach_celeb_block">',i1);
	                            i2 = strTemp.indexOf('<div class="ach_celeb_block">',i2+1);
	                            i2 = strTemp.indexOf('<div class="ach_celeb_block">',i1+1);
	                            strNotice = '<table>'+strTemp.slice(i1,i2)+'</table>';
	
	                        } else if (strTemp.indexOf('<div class="mbox_title"><span>Social Jobs</span></div>')!=-1) {
	                            i1 = strTemp.indexOf('<div class="mbox_title"><span>Social Jobs</span></div>');
	                            i1 = strTemp.indexOf('<tr>',i1);
	                            i2 = strTemp.indexOf('<tr>',i1+1);
	                            strNotice = '<table>'+strTemp.slice(i1,i2)+'</table>';
	
	                        } else {
	                            i1 = strTemp.indexOf('<td class="message_body">');
	                            i2 = strTemp.indexOf('</td>',i1);
	                            strNotice = '<table>'+strTemp.slice(i1,i2)+'</table>';
	
	                        }
	                        strNotice = strNotice.replace(/<script(.|\s)*?\/script>/g, '');
	                        strNotice = strNotice.replace(/color: rgb\(255, 255, 255\)/g, '');
	                        strNotice = strNotice.replace(/color: #fff/g, '');
	                        
	                        //GM_log('strNotice = '+strNotice);
	
	                        LogPush('<strong>'+Self.Type+'</strong><br><table>'+strNotice+'</table>');
	                        NextRequest(aParams[2],aParams[3]);
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 4 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
                	}
	
	            }
	        });
	
	    }
	
	    function doWarStep1(_myUrl, _myParms, _strNotice) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doWarStep1');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	
	            if (iErrorCount <3) {
	                doWarStep1(_myUrl, _myParms, _strNotice);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'POST',
	             url:  _myUrl,
	             data: _myParms,
	             headers: {
	                 'Host':                'facebook.mafiawars.com',
	                 'User-agent':           navigator.userAgent,
	                 'Accept':              '*/*',
	                 'Accept-Language':     'en-us,en;q=0.5',
	                 'Accept-Encoding':     'gzip,deflate',
	                 'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                 'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                 'X-Requested-With':    ' XMLHttpRequest'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2,i3,i4, myUrl;
	                    var strTemp;
	                    var strWarMessage, strWarName, strWarNotice;
	                    var strDetails;
	                    var oSnapShot, oDiv
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 2');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
		                	// all of the responce
		                	strTemp =   _responseDetails.responseText;
		                	strLang = checkLanguage(strTemp);
		                    
	                        //look for who won
	                        strWarName = '';
                            i1 = strTemp.indexOf(aStrLookUp[1][strLang]);
                            if (i1!=-1) {
                                i1 += 33
                                i2 = strTemp.indexOf('<br>',i1);
                                strWarName = strTemp.slice(i1,i2);
                                strWarName = strWarName.replace(/<script(.|\s)*?\/script>/g, '');
                                strWarName = strWarName.replace(/color: rgb\(255, 255, 255\)/g, '');
                                strWarName = strWarName.replace(/color: #fff/g, '');
                            }
                            GM_log('strWarName = '+strWarName);

                            //Look for Message
                            strWarMessage	= '';
                            strWarNotice	= '';
                            i1 = strTemp.indexOf('<td class="message_body">');
                            if (i1 !=-1) {
                                i2 = strTemp.indexOf('</td>',i1);
                                strWarMessage = strTemp.slice(i1+25,i2);
                                // remove any javascript to be safe
                                strWarMessage = strWarMessage.replace(/<script(.|\s)*?\/script>/g, '');
                                strWarMessage = strWarMessage.replace(/color: rgb\(255, 255, 255\)/g, '');
                                strWarMessage = strWarMessage.replace(/color: #fff/g, '');	                                    
                                GM_log('strWarMessage = '+strWarMessage);

                                i1 = strWarMessage.indexOf('<div style="margin');
                                if (i1 == -1) {
                                    strWarNotice = strWarMessage.slice(0,i2);
                                } else {
	                                i1 = strWarMessage.indexOf('">',i1)+2;
                                    i2 = strWarMessage.indexOf('</div>',i1);
                                    strWarNotice = strWarMessage.slice(i1,i2);
                                    i2 = strWarNotice.indexOf('<a href');
                                    if (i2!=-1) strWarNotice = strWarNotice.slice(0,i2);
                                }
                                // remove any javascript to be safe
                                strWarNotice = strWarNotice.replace(/<script(.|\s)*?\/script>/g, '');
                                strWarNotice = strWarNotice.replace(/color: rgb\(255, 255, 255\)/g, '');
                                strWarNotice = strWarNotice.replace(/color: #fff/g, '');
                                GM_log('strWarNotice = '+strWarNotice);
                            }
	
	                        if (strTemp.indexOf(aStrLookUp[2][strLang])!=-1) {
			                        //exit as you cannot participate in this war
			                        GM('You have already participated in this war');
			                        strNotice = _strNotice + '<br>' + aStrLookUp[2][strLang]
			                        LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                NextRequest(aParams[2],aParams[3]);
	                                
	
	                        } else if (strTemp.indexOf(aStrLookUp[3][strLang])!=-1) {
	                            // this war is over
	                            GM_log('War is over');
	
	                            strNotice = _strNotice;
	                            if (strWarNotice != '') 
	                            	strNotice += '<br>'+ strWarNotice
	                            else
			                        strNotice += '<br>'+aStrLookUp[3][strLang]+'.  ' + strWarName + ' has won';
	                            LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                            NextRequest(aParams[2],aParams[3]);
	                        } else {
	                            i1 = strTemp.indexOf(aStrLookUp[4][strLang]);
	                            i2 = strTemp.indexOf('<div class="title">',i1);
	
	                            // This should contain all the attack buttons
	
	                            oDiv = document.createElement('div');
	                            oDiv.innerHTML = '<center>'+strTemp.slice(i1,i2);
	
	                            if (aParams[212]==true)
	                                oSnapShot = getSnapshot(strWarAttackBetray,oDiv)
	                            else
	                                oSnapShot = getSnapshot(strWarAttack,oDiv);
	
	                            // Test to see if we are done
	                            // The fight is either over, or we Won or Lost our fight.
	
	                            if ( (strWarName != '') ||
	                                 (strWarMessage.indexOf(aStrLookUp[5][strLang]) != -1) ||
	                                 (strWarMessage.indexOf(aStrLookUp[6][strLang]) != -1) ||
	                                 (oSnapShot.snapshotLenght == 0)){
	
	                                //no one to attack
	                                GM_log('Done Attacking');

                                    strNotice = _strNotice;
                                    if (strWarNotice != '') strNotice += '<br>'+ strWarNotice;
			                        if (strWarName != '') 	strNotice += '<br>'+aStrLookUp[3][strLang]+'.  ' + strWarName + ' has won';
		                            LogPush('<b>'+Self.Type+'</b><br>'+strNotice);
	                                NextRequest(aParams[2],aParams[3]);
	
	                            } else {
	                                // attemp to attack
	
	                                // add message found to display
	                                strNotice = _strNotice;
	                                if ( strWarNotice != '') strNotice += '<br>' + strWarNotice;
	                                strNotice   +='<br>Found ' +oSnapShot.snapshotLength+' People to attack';
	
	                                // look for local_xw_sig
	                                local_xw_sig = GM_getValue('local_xw_sig');
	                                local_xw_user_id = GM_getValue('local_xw_user_id');
	
	                                myUrl    =  oSnapShot.snapshotItem(getRandRange(0,(oSnapShot.snapshotLength-1))).href
	                                myUrl   +=  '&xw_client_id=8'
	
	                                myParms = 'ajax=1&liteload=1'
	                                myParms += '&sf_xw_user_id=' + local_xw_user_id;
	                                myParms += '&sf_xw_sig=' + local_xw_sig;
	
	                                GM_log('doWarStep1');
	                                doWarStep1(myUrl, myParms, strNotice);
	                            }
	                        }
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoWarStep 1 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                }
	            }
	        });
		}
			
		// FarmVille Code Sections
	    function doFVStep1(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doFVStep1');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doFVStep1(_myUrl,_myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	            method: 'GET',
	            url:  _myUrl,
	            headers: {
	                'Host':            'apps.facebook.com',
	                'User-agent':       navigator.userAgent,
	                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                'Accept-Language': 'en-us,en;q=0.5',
	                'Accept-Encoding': 'gzip,deflate',
	                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl, myUrl2;
	                    var strTemp;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 1');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
	                        strTemp =   _responseDetails.responseText;
	                        i1 = strTemp.indexOf('window.location.replace(')+25;
	                        i2 = strTemp.indexOf(');<',i1);
	                        myUrl = eval("'"+strTemp.slice(i1,i2)+"'");
	                        doFVStep2(myUrl,'');
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 1 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                }
	
	            }
	        });
	
	    }
	    
	    function doFVStep2(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doMWStep2');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            if (iErrorCount <3) {
	                doMWStep2(_myUrl, _myParms);
	            } else {
	                NextRequest(aParams[2],aParams[3]);
	            }
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'GET',
	             url:  _myUrl,
	             headers: {
	                 'Host':            'apps.facebook.com',
	                 'User-agent':       navigator.userAgent,
	                 'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                 'Accept-Language': 'en-us,en;q=0.5',
	                 'Accept-Encoding': 'gzip,deflate',
	                 'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl;
	                    var strTemp;
	                    var strDetails;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Wall Notification - step 2');
	                        NextRequest(aParams[2],aParams[3]);
	                    } else {
	
	                        strTemp =   _responseDetails.responseText;
	
	                        i1 = strTemp.indexOf('<div class="main_giftConfirm_cont">')
	                        
	                        i2 = strTemp.indexOf('"',i1);
	                        myUrl = strTemp.slice(i1,i2);
	                        myUrl = myUrl.replace(/&amp;/g,'&');
	
	                        doMWStep3(myUrl,'');
	                    }
	                } catch(err) {
	                    GM_log('Error: Wall DoMWStep 2 - '+err.message);
	                    NextRequest(aParams[2],aParams[3]);
	                }
	
	            }
	        });
	
	    }
	    
		// main code
	    var iHoldEvent;
	    var myUrl;
	    var nextParms;
	
	    var xmlhttp;
	    var iErrorCount;
	    var bSkipItem;
	    
	    var Self;
	
		try {
	        GM_log('Wall Notifications Start - '+iWallCurrent);
	        
	        Self = this;
	        
	        bSkipItem = false;
	
	        // stop processing if autorun turned off
	        if (bAutoRun) {
	
		        iHoldEvent = iWallCurrent;
		        
		        // ignore things if MW is not valid
		
		        switch (this.AppId) {
		            case '10979261223':
		                // Mafia Wars
		                if (xw_sig_valid == false) {
		                    GM_log('Ignoring MW Wall notice.  Mafia Wars does not appear to be working.');
		                    LogPush('Ignoring MW Wall Notice.  Mafia Wars does not appear to be working.');
		                } else {
		                    //Ignore some types of jobs based on settings
		                    switch (this.Type) {
		                        case 'Ignore':
                        	        bSkipItem = true;
		                            break;
		                        case 'MW_NeedHelp':
		                            if (aParams[204]==false) {LogPush('Skipping Need Help notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_FriendofFriend':
		                            if (aParams[205]==false) {LogPush('Skipping Help Friend of Friend notice');bSkipItem = true; }
		                            break;
		                        case 'MW_NextTarget':
		                            if (aParams[206]==false) {LogPush('Skipping Next Target notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_Bounty':
		                            if (aParams[207]==false) {LogPush('Skipping Bounty notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_LaunderMoney':
		                            if (aParams[209]==false) {LogPush('Skipping Money Laundering notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_SupplyParts':
		                            if (aParams[210]==false) {LogPush('Skipping Supply Parts notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_WarHelp':
		                            if (aParams[211]==false) {LogPush('Skipping War Help Notice'); bSkipItem = true; }
		                            break;
		                        case 'MW_Achievement':
		                        case 'MW_BossBonus':
		                        case 'MW_IcedBonus':
		                        case 'MW_LevelUp':
		                        case 'MW_BonusLoot':
		                        case 'MW_HolidayBonus':
		                        case 'MW_WeaponsDepot':
		                        case 'MW_ChopShop':
		                        case 'MW_Stash':
		                        case 'MW_Robbing':
		                        case 'MW_Burner':
		                            if (aParams[208]==false) { LogPush('Skipping Bonus/Reward/Stash/Burner notice'); bSkipItem = true; }
		                            break;
		                    }
		                }
		
		                if (bSkipItem) {
			                NextRequest(1,aParams[3]);
		                } else {
			                iErrorCount = 0;
		                	GM_log('proccess Wall Notification');
		                	
		                	// fixing href
					        // remove //apps.facebook.com/inthemafia/http&?ref=nf#58;
		    			    this.Action = this.Action.replace(/\/\/apps.facebook.com\/inthemafia\/http&\?ref=nf#58;/g,'')
		                	
		    			    doMWStep1(this.Action,'');
	                	}
		                break;
		
		            case '102452128776':
		                // FarmVille
		                // Ignore some types of jobs based on settings
		                switch (this.Type) {
		                    case 'Ignore':
		                        NextRequest(1,aParams[3]);
		                        break;
		                    case 'BarnRaising':
		                        if (aParams[304]==false) {LogPush('Skipping Barn Raising notice'); bSkipItem = true;}
		                        break;
		                    case 'LendaHand':
		                        if (aParams[305]==false) {LogPush('Skipping Lend a Hand notice'); bSkipItem = true;}
		                        break;
		                    case 'HelpaStallion':
		                        if (aParams[306]==false) {LogPush('Help a Stallion'); bSkipItem = true;}
		                        break;
		                    case 'HatchanEgg':
		                        if (aParams[307]==false) {LogPush('Skipping Hatch an Egg notice'); bSkipItem = true;}
		                        break;
		                    case 'SendDogTreats':
		                        if (aParams[308]==false) {LogPush('Skipping Send Dog Treats notice'); bSkipItem = true;}
		                        break;
		                    case 'AdoptanAminal':
		                        if (aParams[309]==false) {LogPush('Skipping Adopt an Aminal notice'); bSkipItem = true;}
		                        break;
		                    case 'Collectable':
		                        if (aParams[310]==false) {LogPush('Skipping Collectable Notice'); bSkipItem = true;}
		                        break;
		                    case 'Bonus':
		                        if (aParams[311]==false) {LogPush('Skipping Bonus Notice'); bSkipItem = true;}
		                        break;
		                    case 'GetaBushel':
		                        if (aParams[312]==false) {LogPush('Skipping Get a Bushel Notice'); bSkipItem = true;}
		                        break;
		                    case 'Flower':
		                        if (aParams[313]==false) {LogPush('Skipping Flower Notice'); bSkipItem = true;}
		                        break;
		                    case 'FarmHelp':
		                        if (aParams[314]==false) {LogPush('Skipping Farm Help Notice'); bSkipItem = true;}
		                        break;
		                    case 'Fuel':
		                        if (aParams[315]==false) {LogPush('Skipping Fuel Notice'); bSkipItem = true;}
		                        break;
		                    case 'Matriels':
		                        if (aParams[316]==false) {LogPush('Skipping Matriels Notice'); bSkipItem = true;}
		                        break;
		                }
						if (bSkipItem) {
			                NextRequest(1,aParams[3]);
		                } else {
			    	        iErrorCount = 0;
		            	    GM_log('proccess Wall Notification');
		                	//doFVStep1(this.Action,'');
		                	NextRequest(1,aParams[3]);
	                	}
		                break;
	    		}
			} else {
				GM_log('Some one turned the swith off');
			}
	    } catch(err) {
	        GM_log('Error: Wall Main - '+err.message);
	        NextRequest(aParams[2],aParams[3]);
	    }
    }
	
}

// Request Item

function RequestItem () {
    this.Action	    =   '';
    this.Reject     =   '';
    this.Parms      =   '';
    this.From       =   '';
    this.Giftname   =   '';
    this.Gifttype   =   '';
    this.Next       =   null;
    this.Process	= function() {
	    
	    function NextRequest(_delay1, _delay2) {
		    
	        if (Self.Next != null) {
                 iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(_delay1*750,_delay1*1250));
            } else {
	            LogPush('<strong>Finished processing Requests.  Checking again in '+ _delay2 +' minutes.</strong>');
                iRequestCurrent = setTimeout(function (e)  { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(_delay2*50000,_delay2*70000));
            }
            if  (iRequestCurrent < iHoldEvent) {
	            // The browser has reset.  Cancel runaway jobs;
	            clearTimeout(iRequestCurrent);
            }
            
		}
		
		// Mafia Wars Code
	    function MW_AcceptGift() {
	
	        /****  Start Mystery Gift  ****/
	        function Accept_MysteryBag(_oDiv) {
	
	            function doStep1(_myUrl, _myParms) {
	                var iCurrentJob, iWatchDog;
	
	                GM_log('doStep MG 1');
	
	                local_xw_sig        =   GM_getValue('local_xw_sig');
	
	                // start the WatchDog Timer to catch hung requests. 15 seconds.
	                iWatchDog = setTimeout(function (e) {
	                    // abort the current job;
	                    iCurrentJob.abort();
	
	                    // increase the error count
	                    iErrorCount += 1;
	                    if (iErrorCount <3) {
	                        doStep1(_myUrl, _myParms);
	                    } else {
	                        Accept_MysteryBag(_oDiv.nextSibling)
	                    }
	                }, 30000);
	
	                iCurrentJob = GM_xmlhttpRequest({
	                    method: 'POST',
	                    url:  _myUrl,
	                    data: _myParms,
	                    headers: {
	                        'Host':             'facebook.mafiawars.com',
	                        'User-agent':       navigator.userAgent,
	                        'Accept':           'text/plain, */*',
	                        'Accept-Language':  'en-us,en;q=0.5',
	                        'Accept-Encoding':  'gzip,deflate',
	                        'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                        'Content-Type':     'application/x-www-form-urlencoded; charset=UTF-8',
	                        'X-Requested-With': 'XMLHttpRequest'
	                    },
	                    onload: function(_responseDetails) {
	                        try {
	                            var i1,i2, myUrl, myParms;
	                            var strTemp;
	
	                            clearTimeout(iWatchDog);
	                            iErrorCount = 0;
	
	                            if (_responseDetails.status != 200) {
	                                GM_log('Error Trying to Accept Mystery Bag Gift - step 1');
	                                Accept_MysteryBag(_oDiv.nextSibling);
	                            } else {
	
	                                // look for local_xw_sig
	                                local_xw_sig = GM_getValue('local_xw_sig');
	                                local_xw_user_id = GM_getValue('local_xw_user_id');
	
	                                //POST http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=mysterybag&xw_action=mystery_thank&xw_city=3&tmp=a5b34ee369535a217565fd17566c04b6&cb=3c2d5a10693c11dfbea553a6a38fe50b&from_user=p%7C74380332&activehustle=send_gifts
	                                //POST http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=mysterybag&xw_action=mystery_thank&xw_city=3&tmp=a5b34ee369535a217565fd17566c04b6&cb=3c2d5a10693c11dfbea553a6a38fe50b&from_user=p%7C74380332&activehustle=send_gifts&xw_client_id=8 HTTP/1.1
	
	                                i1 = _oDiv.innerHTML.indexOf("mystery_overlay('",i1) + 17
	                                i2 = _oDiv.innerHTML.indexOf("'",i1);
	                                myUrl = 'http://facebook.mafiawars.com/mwfb/'+_oDiv.innerHTML.slice(i1,i2)+' &xw_client_id=8';
	
	                                //ajax=1&liteload=1&sf_xw_user_id=p%7C58583979&sf_xw_sig=c79983037c37df3e7d1981af33f9329e
	
	                                myParms = 'ajax=1&liteload=1'
	                                myParms += '&sf_xw_sig=' + local_xw_sig;
	                                myParms += '&sf_xw_user_id=' + local_xw_user_id;
	
	                                myUrl = myUrl.replace(/&amp;/g,'&');
	
	                                doStep2(myUrl,myParms);
	
	                            }
	                        } catch(err) {
	                            GM_log('Error: Mystery Bag DoStep 1 - '+err.message);
	                            Accept_MysteryBag(_oDiv.nextSibling);
	                        }
	                    }
	                });
	
	            }
	
	            function doStep2(_myUrl, _myParms) {
	
	                var iCurrentJob, iWatchDog;
	
	                GM_log('doStep MG 2');
	
	                local_xw_sig        =   GM_getValue('local_xw_sig');
	
	                // start the WatchDog Timer to catch hung requests. 15 seconds.
	                iWatchDog = setTimeout(function (e) {
	                    // abort the current job;
	                    iCurrentJob.abort();
	
	                    // increase the error count
	                    iErrorCount += 1;
	
	                    if (iErrorCount <3) {
	                        doStep2(_myUrl,_myParms);
	                    } else {
	                        Accept_MysteryBag(_oDiv.nextSibling)
	                    }
	
	                }, 30000);
	
	
	                iCurrentJob = GM_xmlhttpRequest({
	                    method: 'POST',
	                    url:  _myUrl,
	                    data: _myParms,
	                    headers: {
	                        'Host':             'facebook.mafiawars.com',
	                        'User-agent':       navigator.userAgent,
	                        'Content-Type':     'application/x-www-form-urlencoded; charset=UTF-8',
	                        'Accept':           '*/*',
	                        'Accept-Language':  'en-us,en;q=0.5',
	                        'Accept-Encoding':  'gzip,deflate',
	                        'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                        'X-Requested-With': 'XMLHttpRequest'
	                    },
	                    onload: function(_responseDetails) {
	                        try {
	                            var i1,i2, myUrl, myParms;
	                            var strTemp;
	
	                            clearTimeout(iWatchDog);
	                            iErrorCount = 0;
	
	                            strTemp = _responseDetails.responseText;
	
	                            if (_responseDetails.status != 200) {
	                                GM_log('Error Trying to Accept Mystery Bag Gift - step 2');
	                                Accept_MysteryBag(_oDiv.nextSibling)
	                            } else {
	                                i1 = strTemp.indexOf('<div class="mbox_title">');
	
	                                if (i1!=-1) {
	                                    i1 = strTemp.indexOf("<tr>",i1);
	                                    i2 = strTemp.indexOf('</tr>',i1)+5;
	                                    strTemp = '<table>'+strTemp.slice(i1,i2)+'</table>';
	                                    strTemp = strTemp.replace(/color: #fff;/g,'');
	
	                                    LogPush('<strong>Accepting Mystery Bag</strong><br>'+strTemp );
	
	                                    myUrl = 'http://facebook.mafiawars.com/mwfb/mwtrack.php';
	
	                                    doStep3(myUrl,myParms2);
	
	                                } else {
	                                    GM_log('Error Displaying Mystery Bag Results');
	                                    Accept_MysteryBag(_oDiv.nextSibling)
	                                }
	
	                            }
	                        } catch(err) {
	                            GM_log('Error: Mystery Bag DoStep 2 - '+err.message);
	                            Accept_MysteryBag(_oDiv.nextSibling);
	                        }
	                    }
	                });
	
	            }
	
	            function doStep3(_myUrl, _myParms) {
	
	                var iCurrentJob, iWatchDog;
	
	                GM_log('doStep MG 3');
	
	                local_xw_sig        =   GM_getValue('local_xw_sig');
	
	                // start the WatchDog Timer to catch hung requests. 15 seconds.
	                iWatchDog = setTimeout(function (e) {
	                    // abort the current job;
	                    iCurrentJob.abort();
	
	                    // increase the error count
	                    iErrorCount += 1;
	
	                    if (iErrorCount <3) {
	                        doStep1(_myUrl, _myParms);
	                    } else {
	                        Accept_MysteryBag(_oDiv.nextSibling)
	                    }
	
	                }, 30000);
	
	                iCurrentJob = GM_xmlhttpRequest({
	                    method: 'POST',
	                    url:  _myUrl,
	                    data: _myParms,
	                    headers: {
	                        'Host':             'facebook.mafiawars.com',
	                        'User-agent':       navigator.userAgent,
	                        'Accept':           'text/plain, */*',
	                        'Accept-Language':  'en-us,en;q=0.5',
	                        'Accept-Encoding':  'gzip,deflate',
	                        'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                        'Content-Type':     'application/x-www-form-urlencoded; charset=UTF-8',
	                        'X-Requested-With': 'XMLHttpRequest'
	                    },
	                    onload: function(_responseDetails) {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        Accept_MysteryBag(_oDiv.nextSibling)
	
	                    }
	                });
	
	            }
	
	            try {
	                var i1, i2, strTemp;
	                var myUrl, myUrl2, myParms, myParms2;
	                var aTemp;
	
	                if(_oDiv == null) {
	                    NextRequest(aParams[0],aParams[1]);
	
	                } else if(_oDiv.id == undefined) {
	                     Accept_MysteryBag(_oDiv.nextSibling);
	
	                } else if (_oDiv.innerHTML.indexOf('Mystery Bag')!=-1) {
	                    GM_log('accepting Mystery Bag');
	
	                    myUrl       = 'http://facebook.mafiawars.com/mwfb/mwtrack.php';
	                    myParms     = 'ajax=1';
	                    myParms2    = 'ajax=1';
	
	                    i1 = _oDiv.innerHTML.indexOf('ztrack_ajax')
	                    i1 = _oDiv.innerHTML.indexOf("'",i1) + 1
	                    i2 = _oDiv.innerHTML.indexOf("'",i1)
	                    myParms  += '&fname='+_oDiv.innerHTML.slice(i1,i2);
	                    myParms2 += '&fname='+_oDiv.innerHTML.slice(i1,i2);
	
	                    i1 = i2+1;
	
	                    i1 = _oDiv.innerHTML.indexOf("'",i1) + 1
	                    i2 = _oDiv.innerHTML.indexOf("'",i1)
	                    myParms  += '&uid='+_oDiv.innerHTML.slice(i1,i2);
	                    myParms2 += '&uid='+_oDiv.innerHTML.slice(i1,i2);
	                    i1 = i2+1;
	
	                    i1 = _oDiv.innerHTML.indexOf("'",i1) + 1
	                    i2 = _oDiv.innerHTML.indexOf("'",i1)
	                    myParms  += '&secret='+_oDiv.innerHTML.slice(i1,i2);
	                    myParms2 += '&secret='+_oDiv.innerHTML.slice(i1,i2);
	                    i1 = i2+1;
	
	                    i1 = _oDiv.innerHTML.indexOf('{',i1); 
	                    i2 = _oDiv.innerHTML.indexOf(');',i1);
	
	                    eval('aTemp='+_oDiv.innerHTML.slice(i1,i2));
	
	                    for (var name in aTemp){
	                        myParms += '&params['+name+']='+aTemp[name];
	                    }
	
	                    myParms2    += '&params[counter_name]=error_revolver&params[counter_val]='+aTemp['counter_val'];
	
	                    iErrorCount = 0;
	
	                	doStep1(myUrl, myParms);
	
	                } else {
	                    Accept_MysteryBag(_oDiv.nextSibling);
	            	}
	            } catch(err) {
	                GM_log('Error: Mystery Main - '+err.message);
	                Accept_MysteryBag(_oDiv.nextSibling);
	            }
	
	        }
	
	        /****  End Mystery Gift    ****/
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            //extract the embeded URL from responce
	
	                            strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	                            if (i1 ==   -1) {
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	
	                                strTemp = eval("'"+ strTemp+"'");
	                                myUrl = eval(strTemp);
	                                doStep2(myUrl,'');
	                            }
	                        }
	
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep2(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':            'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language': 'en-us,en;q=0.5',
	                    'Accept-Encoding': 'gzip,deflate',
	                    'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myUrl2;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept Gift - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp =   _responseDetails.responseText;

                                i1 = strTemp.indexOf('window.location.replace(')+25;
                                i2 = strTemp.indexOf(');<',i1);
                                //GM_log('MyUrl = '+strTemp.slice(i1,i2));
                                myUrl = eval("'"+strTemp.slice(i1,i2)+"'");
                                //GM_log('MyUrl = '+myUrl);
                                doStep3(myUrl,'');
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep3(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep3');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep3(_myUrl, _myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                 method: 'GET',
	                 url:  _myUrl,
	                 headers: {
	                     'Host':            'apps.facebook.com',
	                     'User-agent':       navigator.userAgent,
	                     'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                     'Accept-Language': 'en-us,en;q=0.5',
	                     'Accept-Encoding': 'gzip,deflate',
	                     'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl;
	                        var strTemp;
	                        var strDetails;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept Gift - step 3');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp =   _responseDetails.responseText;
	
	                            i1 = strTemp.indexOf('<iframe src="')+13;
	                            i2 = strTemp.indexOf('"',i1);
	                            myUrl = strTemp.slice(i1,i2);
	                            myUrl = myUrl.replace(/&amp;/g,'&');
	
	                            doStep4(myUrl,'');
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 3 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep4(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep4');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep4(_myUrl, _myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                 method: 'HEAD',
	                 url:  _myUrl,
	                 headers: {
	                     'Host':            'facebook.mafiawars.com',
	                     'User-agent':       navigator.userAgent,
	                     'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                     'Accept-Language': 'en-us,en;q=0.5',
	                     'Accept-Encoding': 'gzip,deflate',
	                     'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, i3, myUrl;
	                        var strTemp;
	                        var strNotice;
	                        var stopit;
	                        var strLang;
	                        var oDiv, oSnapShot;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept Gift - step 4');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	                            strLang = checkLanguage(strTemp);
	                            
	
	                            if (strTemp.indexOf(aStrLookUp[9][strLang])>-1) {
	                                //GM_log(strTemp)
	
	                                LogPush(aStrLookUp[9][strLang]);
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else if (strTemp.indexOf(aStrLookUp[10][strLang])>-1) {
	
	                                LogPush(aStrLookUp[10][strLang]);
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else if ((strTemp.indexOf('<span class="good">Mystery Bag')!=-1) || (strTemp.indexOf('<span class="good">Red Mystery Bag')!=-1)) {
	                                oDom = document.createElement('div');
	
	                                //GM_log('strTemp = '+strTemp);
	                                i1 = strTemp.indexOf("<div id='msg_box_div_contents_1");
	                                i2 = strTemp.indexOf("<div id='message_box_div_success_black",i1);
	                                oDom.innerHTML = strTemp.slice(i1,i2);
	
	                                if (oDom.childNodes.length >0) {
	                                    //GM_log('Have Status message to look at for Mystery Bags');
	                                    Accept_MysteryBag(oDom.firstChild)
	                                } else {
	                                    NextRequest(aParams[0],aParams[1]);
	                                }
	
	                            } else {
	
	                                // Show a Normal Gift.
	                                i1 = strTemp.indexOf('<div style="border-bottom: 1px dotted #999; margin: 10px auto; text-align: center; font-size: 20px; padding-bottom: 10px;">');
	
	                                
	                                if (i1 == -1) {
	                                    
	                                    i1 = strTemp.indexOf('<div style="border: 1px solid #666666; padding:10px; background-color:black;">');
	                                    if (i1 != -1) {
	                                        i2 = strTemp.indexOf('<br/>',i1);
	                                        LogPush('<b>'+strTemp.slice(i1+78,i2)+'</b>');
	                                        GM_log(strTemp.slice(i1+78,i2));
	                                    } else {
	                                        GM_log('Error finding Gift');
	                                    }
	                                    NextRequest(aParams[0],aParams[1]);
	                                } else {
	                                    i1 = strTemp.indexOf('<div style="float: left;">',i1);
	                                    i2 = strTemp.indexOf('</div>',i1);
	
	                                    GiftItem     =  '<b>'+strTemp.slice(i1+27,i2)+'</b><br>'
	                                    GiftItem    +=  '<table><tr><td><div style="width: 100px; float: left; text-align: center; margin-left: 10px;">';
	
	                                    i1 = strTemp.indexOf('<img', i2);
	                                    i2 = strTemp.indexOf('</div>', i1);
	
	                                    GiftItem    +=  strTemp.slice(i1,i2)+'</div></td><td>';
	
	                                    i1 = strTemp.indexOf('<div style="float: left; text-align: center; width: 200px; padding-top: 55px;">',i2);
	                                    i1 = strTemp.indexOf('<div style="width: 200px; margin-left: 100px; float: left; color: #fff; padding-top: 30px;">',i1);
	
	                                    GiftItem    +=  strTemp.slice(i1,i2)+'</table>';
	
	                                    LogPush(GiftItem);
	                                    NextRequest(aParams[0],aParams[1]);
	                                }
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 4 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	        }
	
	
	        function doStep5(_myUrl, _myParms, _GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	            var i1,i2,strHost;
	
	            GM_log('doStep 5');
	
	            i1 = _myUrl.indexOf('http://')+7;
	            i2 = _myUrl.indexOf('/',i1);
	            strHost = _myUrl.slice(i1,i2);
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep5(_myUrl,_myParms, _GiftItem);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             strHost,
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept Gift - step 5');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	
	                            myUrl        =  'http://www.connect.facebook.com/fbml/ajax/prompt_send.php?__a=1';
	
	                            myParms      =  'app_id=10979261223';
	                            i1           =  strTemp.indexOf('from_user=',i1)+10;
	                            i2           =  strTemp.indexOf('&',i1)
	                            myParms     +=  '&to_ids[0]='+strTemp.slice(i1,i2);
	                            myParms     +=  '&request_type=Mafia%20Wars%20gift&invite=false';
	
	                            i1           =  strTemp.indexOf('content=\\"')+10;
	                            i2           =  strTemp.indexOf('"',i1)-1;
	
	                            strTemp2    =   eval('"'+strTemp.slice(i1,i2)+'"');
	                            strTemp2    =   strTemp2.replace(/&quot;/g,'"');
	                            strTemp2    =   strTemp2.replace(/%/g,"%25");
	                            strTemp2    =   strTemp2.replace(/\$/g,"%24");
	                            strTemp2    =   strTemp2.replace(/</g,"%3C");
	                            strTemp2    =   strTemp2.replace(/>/g,"%3E");
	                            strTemp2    =   strTemp2.replace(/"/g,"%22");
	                            myParms     +=  '&content=' + codeStrings(strTemp2);
	
	                            myParms     +=  '&preview=false&is_multi=false&is_in_canvas=true'
	                            i1          =   strTemp.indexOf('id="req_form')+4;
	                            i2          =   strTemp.indexOf('"',i1);
	                            myParms     +=  '&form_id='+strTemp.slice(i1,i2);
	                            myParms     +=  '&prefill=true&message=&donot_send=false&__d=1'
	                            i1          =   strTemp.indexOf('name="post_form_id" value="')+27;
	                            i2          =   strTemp.indexOf('"',i1);
	                            myParms     +=  '&post_form_id='+strTemp.slice(i1,i2)
	                            i1          =   strTemp.indexOf('fb_dtsg:"',i1)+9;
	                            i2          =   strTemp.indexOf('"',i1);
	                            myParms     +=  '&fb_dtsg='+strTemp.slice(i1,i2);
	                            myParms     +=  '&post_form_id_source=AsyncRequest';
	
	                            doStep6(myUrl,myParms,_GiftItem);
	
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 5 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep6(_myUrl, _myParms, _GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 6');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep6(_myUrl,_myParms, _GiftItem);
	                } else {
	                    LogPush(_GiftItem);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'www.connect.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-SVN-Rev':         unsafeWindow.Env.svn_rev
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                        } else {
	                            GM_log('Adding Thank you');
	                            LogPush(_GiftItem +'<br>Thank you gift Sent');
	                        }
	                        NextRequest(aParams[0],aParams[1]);
	
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 6 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse, bResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        local_xw_sig        =   GM_getValue('local_xw_sig');
	                        local_xw_user_id    =   GM_getValue('local_xw_user_id');
	
	                        if (_responseDetails.status != 200) {
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	                            eval('aResponse= '+strTemp);
	                            strNotice   = aResponse['message'];
	                            GiftItem    = '<b>Mafia Wars Gift Accept:</b><table>'+strNotice+'</table>';
	
	                            if (aResponse["sucess"]== false) {
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else if (aResponse['giftBack'] == undefined) {
	
	                                LogPush(GiftItem);
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else {
	                                eval('bResponse ='+aResponse['giftBack']['eventBody']);
	
	                                myUrl    = 'http://facebook.mafiawars.com/mwfb/'+bResponse['url'];
	                                myUrl   += '&sf_xw_user_id='    + local_xw_user_id;
	                                myUrl   += '&sf_xw_sig='        + local_xw_sig;
	                                myUrl   += '&eventTypeID='      + bResponse['eventTypeID'];
	                                myUrl   += '&eventSNID='        + bResponse['eventSNID'];
	                                myUrl   += '&eventToUIDs='      + bResponse['eventToUID'];
	                                myUrl   += '&eventFromUID='     + bResponse['eventFromUID'];
	                                myUrl   += '&eventBody='        + codeStrings2(aResponse['giftBack']['eventBody']);
	                                myUrl   += '&sf_xw_sig='        + local_xw_sig;
	
	                                doStep11(myUrl, '', GiftItem);
	                            }
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep11(_myUrl, _myParms, _GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 11');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep11(_myUrl, _myParms, _GiftItem);
	                } else {
	                    GM_log('Watchdog Cancel Step 11');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse, bResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	
	                            myUrl    =  'http://www.connect.facebook.com/widgets/serverfbml.php';
	
	                            i1       =  strTemp.indexOf('FB.Facebook.init("')+18;
	                            i2       =  strTemp.indexOf('"',i1);
	
	                            myParms  =  'app_key='+strTemp.slice(i1,i2);
	
	                            i1       =  strTemp.indexOf('"',i2+1)+1;
	                            i2       =  strTemp.indexOf('"',i1);
	                            myParms +=  '&channel_url='+ SendEncode(strTemp.slice(i1,i2));
	
	                            i1       =  strTemp.indexOf('<fb:request-form style="overflow: hidden;" type="Mafia Wars gift"')-10;
	                            i2       =  strTemp.indexOf('</script>',i1);
	                            myParms +=  '&fbml='+SendEncode(strTemp.slice(i1,i2));
	
	                            doStep5(myUrl,myParms,_GiftItem);
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept MW DoStep 11 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        try {
	            GM_log('accept MW Gift');
	            iErrorCount =0 ;
	
	            if (Self.Gifttype.indexOf('MWMessage')== -1) {
	                GM_log('Action FB request');
	                doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	            } else {
	                GM_log('Action MW request');
	                doStep10(Self.Action);
	            }
	        } catch(err) {
	            GM_log('Error: Request Accept MW main - '+err.message);
	            NextRequest(aParams[0],aParams[1]);
	        }
	    }
	
	
	    function MW_SendGift() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep2(_myUrl, _myParms ) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl, _myParms);
	                } else {
	                    LogPush(_GiftItem);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Gift - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp = _responseDetails.responseText;
	                            i1      = strTemp.indexOf('window.location.replace(');
	                            i2      = strTemp.indexOf('");</script>',i1);
	
	                            myUrl   = strTemp.slice(i1+25,i2);
	                            eval('myUrl = "'+myUrl+'"');
	                            doStep3(myUrl, '');
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep3(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep3');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep3(_myUrl, _myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                 method: 'GET',
	                 url:  _myUrl,
	                 headers: {
	                     'Host':            'apps.facebook.com',
	                     'User-agent':       navigator.userAgent,
	                     'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                     'Accept-Language': 'en-us,en;q=0.5',
	                     'Accept-Encoding': 'gzip,deflate',
	                     'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl;
	                        var strTemp;
	                        var strDetails;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Gift - step 3');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp =   _responseDetails.responseText;
	
	                            i1 = strTemp.indexOf('<iframe src="')+13;
	                            i2 = strTemp.indexOf('"',i1);
	                            myUrl = strTemp.slice(i1,i2);
	                            myUrl = myUrl.replace(/&amp;/g,'&');
	
	                            doStep4(myUrl,'');
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 3 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	
	                }
	            });
	
	        }
	
	
	        function doStep4(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep4');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep4(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'HEAD',
	                url:  _myUrl,
	                headers: {
	                    'Host':            'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language': 'en-us,en;q=0.5',
	                    'Accept-Encoding': 'gzip,deflate',
	                    'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2,i3,i4, myUrl, myParms;
	                        var strTemp;
	                        var iGift;
	                        var strName;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Gift - step 4');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	                            local_xw_sig     =   GM_getValue('local_xw_sig');
	
	                            if (strTemp.indexOf('<div class="gift_popup">')!=-1) {
	
	                                i1 = strTemp.indexOf('<div class="gift_popup">');
	
	                                for (var i=0; i<(aParams[202]*1+2);i++) {
	                                    i1 = strTemp.indexOf('<input type="hidden"',i1);
	                                    i1 = strTemp.indexOf('id="',i1)+4;
	                                    i2 = strTemp.indexOf('"',i1);
	                                    i3 = strTemp.indexOf('value="',i2)+7;
	                                    i4 = strTemp.indexOf('"',i3);
	                                    if (strTemp.slice(i1,i2) == 'value_item_id') iGift = strTemp.slice(i1,i2);
	                                }
	
	                                local_xw_sig = GM_getValue('local_xw_sig');
	                                local_xw_user_id = GM_getValue('local_xw_user_id');
	
	                                //value="remote/html_server.php?xw_controller=safehouse&xw_action=answer_send&xw_city=1&tmp=1392f19a32e5a6e5d39c060bb5b82556&cb=1000001824540321271674372&target=1253652918     &time_id=1271672934&gkey=8adeaa0754bbfb55ad53c180f8adde85&gift_box=2
	                                myUrl = 'http://facebook.mafiawars.com/mwfb/';
	                                myUrl += strTemp.slice(i3,i4);
	                                myUrl += '&gift_id=' + iGift +'&xw_client_id=8';
	
	                                myParms = 'ajax=1&liteload=1&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
	
	                                if (strTemp.indexOf("You have already answered to 5 requests for gifts in 24 hours.")!=-1) {
	                                    LogPush('<strong>You have Helped a Crime Spree.</strong><br>You have already answered to 5 requests for gifts in 24 hours.');
	                                } else {
	                                    LogPush('<strong>You have Helped a Crime Spree.</strong><br>Reward has been claimed.');
	                                }
	
	                                doStep5(myUrl,myParms);
	                            } else {
	                                GM_log('Error send MW Gift - Gift popup missing - step 4');
	                                NextRequest(aParams[0],aParams[1]);
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 4 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep5(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep5');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	                if (iErrorCount <3) {
	                    doStep5(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           '*/*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded; charset=UTF-8',
	                    'X-Requested-With': 'XMLHttpRequest'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Send MW Gift - step 5');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            GM_log('Gift Send and rewarded claimed');
	                            NextRequest(aParams[0],aParams[1]);
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 5 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	                            eval('aResponse= '+strTemp);
	
	                            strNotice   = aResponse["message"];
	                            i1 = strNotice.indexOf('<a ')
	
	                            if (aResponse["sucess"]== false) {
	                                GM_log('Do Step 10 Error - '+strNotice);
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else if (i1 == -1) {
	
	                                LogPush('<b>'+strNotice+'</b>');
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else {
	                                GiftItem = '<b>'+strNotice.slice(0,i1)+'</b>'
	                                LogPush(GiftItem);
	
	                                i1 = strNotice.indexOf('href="',i1);
	                                i2 = strNotice.indexOf('" target=',i1);
	
	                                myUrl = strNotice.slice(i1+6,i2);
	
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Send MW DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	
	                }
	            });
	
	        }
	
	        GM_log('Send MW Gift');
	
	        iErrorCount =0 ;
	
	        if (Self.Gifttype.indexOf('MWMessage')== -1) {
	            GM_log('Action FB request');
	            doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	        } else {
	            GM_log('Action MW request');
	            doStep10(Self.Action);
	        }
	
	    }
	    function MW_Join() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Join - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                GM_log('no GoUri');
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join MW DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep2(_myUrl, _myParms ) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl, _myParms);
	                } else {
	                    LogPush(_GiftItem);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error send MW Join - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp = _responseDetails.responseText;
	                            i1      = strTemp.indexOf('window.location.replace(');
	                            i2      = strTemp.indexOf('");</script>',i1);
	
	                            myUrl   = strTemp.slice(i1+25,i2);
	                            eval('myUrl = "'+myUrl+'"');
	                            doStep3(myUrl, '');
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join MW DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep3(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doStep3');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	
	            if (iErrorCount <3) {
	                doStep3(_myUrl, _myParms);
	            } else {
	                NextRequest(aParams[0],aParams[1]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'GET',
	             url:  _myUrl,
	             headers: {
	                 'Host':            'apps.facebook.com',
	                 'User-agent':       navigator.userAgent,
	                 'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                 'Accept-Language': 'en-us,en;q=0.5',
	                 'Accept-Encoding': 'gzip,deflate',
	                 'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl;
	                    var strTemp;
	                    var strDetails;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error send MW Join - step 3');
	                        NextRequest(aParams[0],aParams[1]);
	                    } else {
	
	                        strTemp =   _responseDetails.responseText;
	
	                        i1 = strTemp.indexOf('<iframe src="')+13;
	                        i2 = strTemp.indexOf('"',i1);
	                        myUrl = strTemp.slice(i1,i2);
	                        myUrl = myUrl.replace(/&amp;/g,'&');
	
	                        doStep4(myUrl,'');
	
	                    }
	                } catch(err) {
	                    GM_log('Error: Request Join MW DoStep 3 - '+err.message);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }
	        });
	
	    }
	
	
	    function doStep4(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('doStep4');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	
	            if (iErrorCount <3) {
	                doStep4(_myUrl,_myParms);
	            } else {
	                NextRequest(aParams[0],aParams[1]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	            method: 'HEAD',
	            url:  _myUrl,
	            headers: {
	                'Host':            'facebook.mafiawars.com',
	                'User-agent':       navigator.userAgent,
	                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                'Accept-Language': 'en-us,en;q=0.5',
	                'Accept-Encoding': 'gzip,deflate',
	                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1, i2, i3, i4, myUrl, myParms;
	                    var strTemp;
	                    var strNotice;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error send MW Gift - step 4');
	                        NextRequest(aParams[0],aParams[1]);
	                    } else {
	
	                        strTemp = _responseDetails.responseText;
	
	                        local_xw_sig     =   GM_getValue('local_xw_sig');
	
	                        if (strTemp.indexOf('<ul class="incoming_requests clearfix">')!=-1) {
	
	                            i1 = strTemp.indexOf('<ul class="incoming_requests clearfix">');
	                            i2 = strTemp.indexOf('</ul>',i1);
	
	                            strTemp = strTemp.slice(i1,i2);
	
	                            i1 = 0
	
	                            do {
	                                i1 = strTemp.indexOf('<li>',i1);
	                                GM_log('i1 = '+i1);
	                                if (i1!=-1) {
	                                    i1 = i1+1
	                                    i3 = strTemp.indexOf('<img src="',i1);
	                                    i4 = strTemp.indexOf('</span>',i3);
	
	                                    strNotice = strTemp.slice(i3,i4);
	
	                                    i3 = strTemp.indexOf("this.href='",i1);
	                                    i4 = strTemp.indexOf("'+local_xw_sig",i3);
	
	                                    myUrl = strTemp.slice(i3+11,i4)+local_xw_sig
	
	                                    if (myUrl.indexOf(Join_id) != -1) {
	
	                                        GM_log('Found Member to add to mafia');
	                                        doStep5(myUrl,'');
	                                    }
	                                } else {
	                                    GM_log('Could not find user to Join');
	                                    LogPush('<Strong>MW Join</strong><br>Could not find user.  Possibly already joined');
	                                    NextRequest(aParams[0],aParams[1]);
	                                }
	                            } while (i1 != -1)
	
	                        } else {
	                            GM_log('Error with MW Join');
	                            NextRequest(aParams[0],aParams[1]);
	                        }
	                    }
	                } catch(err) {
	                    GM_log('Error: Request Join MW DoStep 4 - '+err.message);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	            }
	        });
	
	    }
	
	    function doStep5(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep5');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep5(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	                        var strDetails;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Send MW Gift - step 5');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp     = _responseDetails.responseText;
	                            i1          = strTemp.indexOf('<td class="message_body">');
	                            if (i1!=-1) {
	                                i2          = strTemp.indexOf('</td>',i1);
	                                strDetails  = strTemp.slice(i1+25,i2);
	                                LogPush('<strong>MW Join<strong><br>'+strDetails);
	                            }
	
	                            GM_log('MW Join sucessfull');
	                            NextRequest(aParams[0],aParams[1]);
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join MW DoStep 5 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'facebook.mafiawars.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	                            eval('aResponse= '+strTemp);
	
	                            strNotice   = aResponse["message"];
	
	                            if (aResponse["sucess"]== false) {
	                                GM_log('Do Step 10 Error - '+strNotice);
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else{
	
	                                LogPush('<b>MW Join</b><br>'+strNotice);
	                                NextRequest(aParams[0],aParams[1]);
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join MW DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        try {
	            GM_log('Send MW Join');
	
	            var Join_id;
	            var i1,i2;
	
	            i1  =   Self.Parms.indexOf('[from_id]=')+10;
	            i2  =   Self.Parms.indexOf('&',i1);
	
	            Join_id = Self.Parms.slice(i1,i2);
	
	            iErrorCount =0 ;
	
	            if (Self.Gifttype.indexOf('MWMessage')== -1) {
	                GM_log('Action FB request');
	                doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	            } else {
	                GM_log('Action MW request');
	                doStep10(Self.Action);
	            }
	        } catch(err) {
	            GM_log('Error: Request Join MW Main');
	            NextRequest(aParams[0],aParams[1]);
	        }
	
	    }
		
		
		
		
		// FarmVille Code
	
	    function FV_AcceptGift() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                            return;
	                        } else {
	
	                            strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                GM_log('no GoUri');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep2(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Content-Type':     'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myUrl2, myParms;
	                        var strTemp,strTemp2;
	                        var GiftItem;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                            return;
	                        } else {
	
	                            strTemp =   _responseDetails.responseText;
	
	                            if (strTemp.indexOf('gifterror.php?type=notfound')!=-1) {
	                                LogPush('An error occured while accepting this FarmVille gift. The gift data was not found.  Please remember to accept each gift right away.');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else if (strTemp.indexOf('<div class="giftLimit">')!=-1) {
	
	                                i1          = strTemp.indexOf('<div class="giftLimit">');
	                                i2          = strTemp.indexOf('</div>',i1);
	
	                                // a little testing
	                                if (strTemp.indexOf('You have already accepted this gift') != -1) {
	                                    LogPush('<b>'+strTemp.slice(i1+23,i2)+'</b>');
	                                } else if (strTemp.indexOf('The gift you tried to accept was LIMITED EDITION and is no longer available') != -1) {
	                                    LogPush('<b>'+strTemp.slice(i1+23,i2)+'</b>');
	                                } else {
	                                    LogPush('<b>'+strTemp.slice(i1+23,i2)+'</b><br>FV Gift Accepting is being turned off for Two (2) Hour.  Please accept some of your FV gifts.');
	
	                                    FV_accept_ignore    = Math.floor(new Date().valueOf()/1000) + 120*60;
	                                }
	
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else if (strTemp.indexOf('<div class="giftConfirm_img">')!=-1) {
	
	                                i1          = strTemp.indexOf('<div class="giftConfirm_name">');
	                                i2          = strTemp.indexOf('</div>',i1);
	                                GiftItem    = '<b>You just accepted a '+strTemp.slice(i1+30,i2);
	
	                                i1          = strTemp.indexOf('<div class="giftFrom_name">');
	                                i2          = strTemp.indexOf('</div>',i1);
	                                GiftItem   += ' from '+strTemp.slice(i1+27,i2);
	
	                                i1          = strTemp.indexOf('<div class="giftConfirm_img">');
	                                i2          = strTemp.indexOf('</div>',i1);
	                                GiftItem   += '</b><br>'+strTemp.slice(i1+29,i2);
	
	                                //GM_log('GiftItem = '+GiftItem);
	
	
	                                // check for thank you gift
	                                i1      = strTemp.indexOf('<div class="thank_you_gift">');
	                                if (i1==-1) {
	                                    // no thank you gift
	                                    LogPush(GiftItem);
	                                    NextRequest(aParams[0],aParams[1]);
	                                    return;
	
	                                } else {
	                                    // found the thank you gift
	
	                                    myUrl        =  'http://apps.facebook.com/fbml/ajax/prompt_send.php?__a=1';
	
	                                    myParms      =  'app_id=102452128776';
	                                    i1           =  strTemp.indexOf('giftRecipient=',i1)+14;
	                                    i2           =  strTemp.indexOf('&',i1)
	                                    myParms     +=  '&to_ids[0]='+strTemp.slice(i1,i2);
	                                    myParms     +=  '&request_type=FarmVille%20Gift&invite=false';
	
	                                    i1           =  strTemp.indexOf('content="',i1)+9;
	                                    i2           =  strTemp.indexOf('"',i1);
	
	                                    strTemp2    =   strTemp.slice(i1,i2)
	
	                                    strTemp2    =   strTemp2.replace(/&quot;/g,'"');
	                                    strTemp2    =   strTemp2.replace(/%/g,"%25");
	                                    strTemp2    =   strTemp2.replace(/\$/g,"%24");
	                                    strTemp2    =   strTemp2.replace(/</g,"%3C");
	                                    strTemp2    =   strTemp2.replace(/>/g,"%3E");
	                                    strTemp2    =   strTemp2.replace(/"/g,"%22");
	                                    myParms     +=  '&content=' + codeStrings(strTemp2);
	
	                                    myParms     +=  '&preview=false&is_multi=false&is_in_canvas=true'
	                                    i1          =   strTemp.indexOf('id="',i1)+4;
	                                    i2          =   strTemp.indexOf('"',i1);
	                                    myParms     +=  '&form_id='+strTemp.slice(i1,i2);
	                                    myParms     +=  '&prefill=true&message=&donot_send=false&__d=1'
	                                    i1          =   strTemp.indexOf('post_form_id:"')+14;
	                                    i2          =   strTemp.indexOf('"',i1);
	                                    myParms     +=  '&post_form_id='+strTemp.slice(i1,i2)
	
	                                    i1          =   strTemp.indexOf('fb_dtsg:"',i1)+9;
	                                    i2          =   strTemp.indexOf('"',i1);
	                                    myParms     +=  '&fb_dtsg='+strTemp.slice(i1,i2);
	                                    myParms     +=  '&post_form_id_source=AsyncRequest';
	
	                                    //next url
	                                    i1          =   strTemp.indexOf('<form action="')+14;
	                                    i2          =   strTemp.indexOf('"',i1);
	
	                                    myUrl2      =   strTemp.slice(i1,i2);
	                                    myUrl2      =   myUrl2.replace(/&amp;/g,'&');
	
	                                    doStep3(myUrl, myParms, myUrl2, GiftItem);
	                                }
	                            } else {
	                                GM_log('FV Accept Gift Failed - Cannot find giftconfirm image');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	                            }
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep3(_myUrl, _myParms, _myUrl2, _GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep3');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep3(_myUrl, _myParms, _myUrl2, _GiftItem);
	                } else {
	                    LogPush(_GiftItem);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-SVN-Rev':         unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 3');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                            return;
	
	                        } else {
	                            LogPush(_GiftItem +'<br>Thank you gift Sent');
	                            doStep4(_myUrl2,'');
	                            return;
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 3 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep4(_myUrl, _myParms ) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep4');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep4(_myUrl, _myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to send return FV Gift - step 4');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp = _responseDetails.responseText;
	                            i1      = strTemp.indexOf('window.location.replace(');
	                            i2      = strTemp.indexOf('");</script>',i1);
	
	                            myUrl   = strTemp.slice(i1+25,i2);
	                            eval('myUrl = "'+myUrl+'"');
	                            doStep5(myUrl, '');
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 5 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	
	                }
	            });
	
	        }
	
	        function doStep5(_myUrl, _myParms ) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep5');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep5(_myUrl, _myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                data: _myParms,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to send return FV Gift - step 5');
	
	                        } else {
	                            GM_log('fv gift sent');
	                        }
	                        NextRequest(aParams[0],aParams[1]);
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 5 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'www.farmville.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                             
                                strTemp     = _responseDetails.responseText;
                                eval('aResponse= '+strTemp);

                                strNotice   = aResponse["message"];

                                if (aResponse["success"] == false) {
                                    NextRequest(aParams[0],aParams[1]);

                                } else {
                                    GiftItem = '<b>'+strNotice +'</b>'


                                    if ( aResponse["giftBack"] == undefined) {

                                        LogPush('<b>'+GiftItem+'</b>');
                                        NextRequest(aParams[0],aParams[1]);

                                    } else {

                                        myUrl    =  'http://www.farmville.com/';
                                        myUrl   +=  aResponse["giftBack"]["url"];
                                        myUrl   +=  '?eventTypeID='+aResponse["giftBack"]["eventTypeID"];
                                        myUrl   +=  '&eventSNID='+aResponse["giftBack"]["eventSNID"];
                                        myUrl   +=  '&eventToUIDs='+aResponse["giftBack"]["eventToUIDs"];
                                        myUrl   +=  '&eventFromUID='+aResponse["giftBack"]["eventFromUID"];
                                        myUrl   +=  '&eventBody='+SendEncode(aResponse['giftBack']['eventBody']);

                                        doStep11(myUrl,GiftItem);
                                    }
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep11(_myUrl,_GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 11');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep11(_myUrl,_GiftItem);
	                } else {
	                    GM_log('Watchdog Cancel Step 11');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'www.farmville.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp = _responseDetails.responseText;
	                            i1 = strTemp.indexOf('href="');
	                            if (i1== -1) {
	                                GM_log('No href in FV gift accept');
	                                LogPush(_GiftItem);
	                                NextRequest(aParams[0],aParams[1]);
	                            } else {
	                                i2 = strTemp.indexOf('"',i1);
	                                myUrl = 'http://www.farmville.com/' + strTemp.slice(i1+6,i2);
	
	                                doStep12(myUrl,_GiftItem);
	                            }
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 11 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep12(_myUrl,_GiftItem) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 12');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep12(_myUrl,_GiftItem);
	                } else {
	                    GM_log('Watchdog Cancel Step 12');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'www.farmville.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            LogPush(_GiftItem+'<br>Thank You Gift Sent');
	                            NextRequest(aParams[0],aParams[1]);
	                        }
	
	                    } catch(err) {
	                        GM_log('Error: Request Accept FV DoStep 12 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        try {
	            GM_log('FV Accept Gift');
	
	            iErrorCount =0 ;
	
	            if (Self.Gifttype.indexOf('FVMessage')== -1) {
	                GM_log('Action FB request');
	                doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	            } else {
	                GM_log('Action FV request');
	                doStep10(Self.Action);
	            }
	        } catch(err) {
	            GM_log('Error: Request Accept FV Main - '+err.message);
	            NextRequest(aParams[0],aParams[1]);
	        }
	
	    }
	
	    function FV_SendGift() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                           strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                GM_log('no GoUri');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV Send DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	        }
	
	        function doStep2(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:    _myUrl,
	                headers: {
	                    'Host':            'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language': 'en-us,en;q=0.5',
	                    'Accept-Encoding': 'gzip,deflate',
	                    'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	                        var strName, strValue;
	                        var strNotice;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp   =   _responseDetails.responseText;
	                            i1 = strTemp.indexOf('<div class="main_giftConfirm_cont">');
	                            i2 = strTemp.indexOf('<div class="morePending_cont">',i1);
	
	                            strNotice = strTemp.slice(i1,i2);
	                            strNotice = strNotice.replace(/<h3>/g,'');
	                            strNotice = strNotice.replace(/<\/h3>/g,'');
	
	                            LogPush('<strong>FarmVille Send Gift<strong><br><table>' + strNotice + '</table>');
	                            NextRequest(aParams[0],aParams[1]);
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV Send DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'www.farmville.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	                            eval('aResponse= '+strTemp);
	                            strNotice   = aResponse["message"];
	
	                            if (aResponse["sucess"]== false) {
	                                NextRequest(aParams[0],aParams[1]);
	                            } else{
	                                LogPush('<b>'+strNotice+'</b>');
	                                NextRequest(aParams[0],aParams[1]);
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV Send DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        try {
	            GM_log('FV Send gift');
	            iErrorCount =0 ;
	
	            if (Self.Gifttype.indexOf('FVMessage')== -1) {
	                GM_log('Action FB request');
	                doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	            } else {
	                GM_log('Action FV request');
	                doStep10(Self.Action);
	            }
	        } catch(err) {
	            GM_log('Error: Request Join FV Send main - '+err.message);
	            NextRequest(aParams[0],aParams[1]);
	        }
	
	
	    }
	
	    function FV_Join() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                           strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                GM_log('no GoUri');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	        }
	
	        function doStep2(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:    _myUrl,
	                headers: {
	                    'Host':            'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language': 'en-us,en;q=0.5',
	                    'Accept-Encoding': 'gzip,deflate',
	                    'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	                        var strName, strValue;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Join - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp   =   _responseDetails.responseText;
	
	                            LogPush('<strong>You have accepted a FarmVille Neighbour request.<strong>');
	                            NextRequest(aParams[0],aParams[1])
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	
	        }
	
	        function doStep10(_myUrl) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep 10');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep10(_myUrl);
	                } else {
	                    GM_log('Watchdog Cancel Step 10');
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'www.farmville.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'application/json, text/javascript, */*',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':     'application/x-www-form-urlencoded',
	                    'X-Requested-With': 'XMLHttpRequest'
	
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1, i2, myUrl, myParms;
	                        var strTemp, strTemp2;
	                        var strLang;
	                        var strNotice;
	                        var GiftItem;
	                        var aResponse;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error in Response');
	                            LogPush(_GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	                            strTemp     = _responseDetails.responseText;
	                            eval('aResponse= '+strTemp);
	
	                            strNotice   = aResponse["message"];
	
	                            GiftItem = '<b>FV Join</b><br>'+strNotice;
	                            LogPush(GiftItem);
	                            NextRequest(aParams[0],aParams[1]);
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Join FV DoStep 10 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        try {
	            GM_log('FV Join');
	            iErrorCount =0 ;
	
	            if (Self.Gifttype.indexOf('FVMessage')== -1) {
	                GM_log('Action FB request');
	                doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	            } else {
	                GM_log('Action FV request');
	                doStep10(Self.Action);
	            }
	        } catch(err) {
	            GM_log('Error: Request Join FV Main - '+err.message);
	            NextRequest(aParams[0],aParams[1]);
	        }
	    }
	
	    function FV_ClaimBonus() {
	
	        function doStep1(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep1');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep1(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'POST',
	                url:    _myUrl,
	                data:   _myParms,
	                headers: {
	                    'Host':                'www.facebook.com',
	                    'User-agent':           navigator.userAgent,
	                    'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':     'en-us,en;q=0.5',
	                    'Accept-Encoding':     'gzip,deflate',
	                    'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                    'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                    'Referer':             'http://www.facebook.com/reqs.php',
	                    'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 1');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                           strTemp = _responseDetails.responseText;
	
	                            i1      =   strTemp.indexOf('goURI');
	
	                            if (i1 == -1) {
	                                GM_log('no GoUri');
	                                NextRequest(aParams[0],aParams[1]);
	                                return;
	
	                            } else {
	                                i2        =   strTemp.indexOf(');"]',i1);
	                                strTemp   =   strTemp.slice(i1+6,i2);
	                                strTemp = eval("'"+ strTemp + "'");
	                                myUrl   = eval(strTemp);
	                                doStep2(myUrl,'');
	                            }
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Bonus FV DoStep 1 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	        }
	
	        function doStep2(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep2');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep2(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:    _myUrl,
	                headers: {
	                    'Host':            'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language': 'en-us,en;q=0.5',
	                    'Accept-Encoding': 'gzip,deflate',
	                    'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	                        var strName, strValue;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 2');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp   =   _responseDetails.responseText;
	
	                            if (strTemp.indexOf('<div class="alreadyReceivedStimulusContent">')!=-1) {
	                                LogPush('<strong>FarmVille Bonus Claimed</strong><br>Howdy Partner! You have already claimed your bonus package.');
	                                NextRequest(aParams[0],aParams[1]);
	
	                            } else if (strTemp.indexOf('<div class="chooseStimulusGiftContainer">')!=-1) {
	
	                                i1 = strTemp.indexOf('<div class="chooseStimulusGiftContainer">');
	                                for (var i=0;i<aParams[305];i++)
	                                    i1 = strTemp.indexOf('<form action="',i1)+14;
	                                i2 = strTemp.indexOf('"',i1);
	
	                                myUrl = strTemp.slice(i1,i2);
	
	                                myParms = '';
	                                i1 = strTemp.indexOf('<input type="hidden"',i1);
	                                i2 = strTemp.indexOf('<input type="submit"',i1);
	                                strTemp = strTemp.slice(i1,i2);
	
	                                do {
	                                    i1 = strTemp.indexOf('name="',i1);
	                                    if(i1==-1) {
	                                        break;
	                                    } else {
	                                        i1 += 6;
	                                        i2 = strTemp.indexOf('"',i1);
	                                        strName = strTemp.slice(i1,i2);
	                                        i1 = strTemp.indexOf('value="',i1)+7;
	                                        i2 = strTemp.indexOf('"',i1);
	                                        strValue = strTemp.slice(i1,i2);
	                                        if (strName == 'fb_sig_ext_perms') strValue = codeStrings(strValue);
	                                        if (i>0) myParms += '&';
	                                        myParms += strName +'='+strValue;
	                                    }
	                                } while (true)
	
	                                doStep3(myUrl, myParms);
	                            } else {
	                                GM_log('Error with Bonus Claim');
	                                NextRequest(aParams[0],aParams[1]);
	                            }
	
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Bonus FV DoStep 2 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	
	                }
	            });
	
	        }
	
	        function doStep3(_myUrl, _myParms) {
	
	            var iCurrentJob, iWatchDog;
	
	            GM_log('doStep3');
	
	            local_xw_sig        =   GM_getValue('local_xw_sig');
	
	            // start the WatchDog Timer to catch hung requests. 15 seconds.
	            iWatchDog = setTimeout(function (e) {
	                // abort the current job;
	                iCurrentJob.abort();
	
	                // increase the error count
	                iErrorCount += 1;
	
	                if (iErrorCount <3) {
	                    doStep3(_myUrl,_myParms);
	                } else {
	                    NextRequest(aParams[0],aParams[1]);
	                }
	
	            }, 30000);
	
	
	            iCurrentJob = GM_xmlhttpRequest({
	                method: 'GET',
	                url:  _myUrl,
	                headers: {
	                    'Host':             'apps.facebook.com',
	                    'User-agent':       navigator.userAgent,
	                    'Accept':           'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                    'Accept-Language':  'en-us,en;q=0.5',
	                    'Accept-Encoding':  'gzip,deflate',
	                    'Accept-Charset':   'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                },
	                onload: function(_responseDetails) {
	                    try {
	                        var i1,i2, myUrl, myParms;
	                        var strTemp;
	                        var GiftItem;
	
	                        clearTimeout(iWatchDog);
	                        iErrorCount = 0;
	
	                        if (_responseDetails.status != 200) {
	                            GM_log('Error Trying to Accept FV Gift - step 3');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else {
	
	                            strTemp   =   _responseDetails.responseText;
	                            i1 = strTemp.indexOf('transparent url("')+17;
	                            i2 = strTemp.indexOf('"');
	                            GiftItem = strTemp.slice(i1,i2);
	
	                            LogPush('<strong>FarmVille Bonus Claimed</strong><br><img width=50% src="'+GiftItem+'"');
	                            NextRequest(aParams[0],aParams[1]);
	                        }
	                    } catch(err) {
	                        GM_log('Error: Request Bonus FV DoStep 3 - '+err.message);
	                        NextRequest(aParams[0],aParams[1]);
	                    }
	                }
	            });
	        }
	
	        try {
	            GM_log('FV Claim Bonus');
	            iErrorCount =0 ;
	            doStep1(strBase,Self.Parms+Self.Action+'&post_form_id_source=AsyncRequest');
	        } catch(err) {
	            GM_log('Error: Request Bonus FV Main - '+err.message);
	            NextRequest(aParams[0],aParams[1]);
	        }
	
	    }
				
		// FaceBook Code
	    function FB_do(_myUrl, _myParms) {
	
	        var iCurrentJob, iWatchDog;
	
	        GM_log('FB do request');
	
	        local_xw_sig        =   GM_getValue('local_xw_sig');
	
	        // start the WatchDog Timer to catch hung requests. 15 seconds.
	        iWatchDog = setTimeout(function (e) {
	            // abort the current job;
	            iCurrentJob.abort();
	
	            // increase the error count
	            iErrorCount += 1;
	            GM_log('WatchDog - FB: '+iErrorCount);
	
	            if (iErrorCount <3) {
	                FB_do(_myUrl, _myParms)
	            } else {
	                NextRequest(aParams[0],aParams[1]);
	            }
	
	        }, 30000);
	
	        iCurrentJob = GM_xmlhttpRequest({
	             method: 'POST',
	             url:  _myUrl,
	             data: _myParms,
	             headers: {'Host':                'www.facebook.com',
	                       'User-agent':           navigator.userAgent,
	                       'Accept':              'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	                       'Accept-Language':     'en-us,en;q=0.5',
	                       'Accept-Encoding':     'gzip,deflate',
	                       'Accept-Charset':      'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	                       'Content-Type':        'application/x-www-form-urlencoded; charset=UTF-8',
	                       'Referer':             'http://www.facebook.com/reqs.php',
	                       'X-SVN-Rev':            unsafeWindow.Env.svn_rev
	            },
	            onload: function(_responseDetails) {
	                try {
	                    var i1,i2, myUrl;
	                    var strTemp;
	                    var strDetails;
	
	                    clearTimeout(iWatchDog);
	                    iErrorCount = 0;
	
	                    strTemp = _responseDetails.responseText;
	
	                    if (_responseDetails.status != 200) {
	                        GM_log('Error Friend Request');
	                        NextRequest(aParams[0],aParams[1]);
	                        return;
	
	                    } else {
	                            // You ignored a suggestion to add <a href=\\\"http:\\\/\\\/www.facebook.com\\\/profile.php?id=100000199047756\\\">John Van Alst<\\\/a> as a friend
	
	                        i1 = strTemp.indexOf('HTML(\"');
	                        i2 = strTemp.indexOf('{"msg":"');
	
	                        if (i1!=-1) {
	                            i2 = strTemp.indexOf('\")',i1);
	                            strDetails = eval("'"+strTemp.slice(i1+7,i2)+"'");
	                            LogPush('<strong>'+strTemp+'</strong>');
	                            NextRequest(aParams[0],aParams[1]);
	                        } else if (i2!=-1) {
	                            i1 = i2;
	                            i2 = strTemp.indexOf('","',i1);
	                            strDetails = eval('"'+strTemp.slice(i1+8,i2)+'"');
	                            LogPush('<strong>'+strDetails+'</strong>');
	                            NextRequest(aParams[0],aParams[1]);
	                        }
	                    }
	                } catch(err) {
	                    GM_log('Error: Request Join FV DoStep 1 - '+err.message);
	                    NextRequest(aParams[0],aParams[1]);
	                }
	            }
	        });
	
	    }
	    
	    // Main Code
	    
	    var iHoldEvent;
		var Self;
	    var i1,i2,i3,i4;
	    var strTemp;

	    var aCat;
	    var xmlhttp;
	    var myURL;
	
	    var iErrorCount;

	    Self = this;
	    iHoldEvent = iRequestCurrent;

	    // stop processing if autorun turned off
	    if (bAutoRun) {
		    aCat    = Self.Gifttype.split('_');
		    
		    switch (aCat[0]) {
		        case 'friend':
		            switch (aCat[1]) {
		                case 'suggestion':
		                    if (aParams[100]==2) {
		
		                        if (aParams[101]=='0')
		                            FB_do(strBase,strAccept+Self.Parms+'&params[lists]=&post_form_id_source=AsyncRequest')
		                        else
		                            FB_do(strBase,strAccept+Self.Parms+'&params[lists]=[' + aParams[101]+']' + '&post_form_id_source=AsyncRequest');
		
		                    } else if (aParams[100]==1) {
		                        FB_do(strBase,strReject+Self.Parms);
		
		                    } else {
		                        LogPush('Skipping Friend Suggestion');
		                        NextRequest(1,aParams[1]);
		                    }
		                    break;
		                case 'connect':
		                    GM_log('Found Friend Connect');
		                    if (aParams[102]==2) {
		
		                        if (aParams[103]=='0') {
		                            FB_do(strBase,strAccept+Self.Parms+'&params[lists]&post_form_id_source=AsyncRequest');
		                        } else {
		                            FB_do(strBase,strAccept+Self.Parms+'&params[lists]=[' + aParams[103]+']&post_form_id_source=AsyncRequest');
		                        }
		
		                    } else if (aParams[102]==1) {
		                        FB_do(strBase,strReject+Self.Parms);
		
		                    } else {
		                        LogPush('Skipping Friend Request');
		                        NextRequest(1,aParams[1]);
		                    }
		                    break;
		            }
		            break;
		
		        case 'event':
		            if (aParams[104]==1) {
		                FB_do(strBase,Self.Parms+'&post_form_id_source=AsyncRequest');
		            } else {
		                LogPush('Skipping Event');
		                NextRequest(1,aParams[1]);
		            }
		            break;
		
		        case 'fbpage':
		            if (aParams[105]==1) {
		                FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		            } else {
		                LogPush('Skipping Page Suggestion');
		                NextRequest(1,aParams[1]);
		            }
		            break;
		
		        case 'group':
		            if (aParams[106]==1) {
		                FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		            } else {
		                LogPush('Skipping Group Invitation');
		                NextRequest(1,aParams[1]);
		            }
		            break;
		
		        case 'confirm':
		            switch (aCat[1]) {
		                case '10979261223':
		                    // Mafiawars
		                    if (xw_sig_valid == false) {
		                        LogPush('Skipping Mafia Wars item.  Mafia wars does not appear to be working.');
		                        NextRequest(aParams[0],aParams[1]);
		                    } else if (Self.Action.indexOf('accept_gift') != -1) {
		                        //Accept Gifts
		                        if (aParams[200]==2) {
		                            MW_AcceptGift();
		                        } else if (aParams[200]==1) {
		                           FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    } else if (Self.Action.indexOf('answer_gift') != -1) {
		                        //Send Gifts
		                        if (aParams[201]==2) {
		                            MW_SendGift();
		                        } else if (aParams[201]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    } else {
		                        //join
		                        if (aParams[203]==2) {
		                            MW_Join();
		                        } else if (aParams[203]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    }
		                    break;
		
		                case '102452128776':
		                    // FarmVille
		                    if (Self.Action.indexOf('giftaccept') != -1) {
		                        //Accept Gifts
		                        if (aParams[300]==2) {
		                            if ( FV_accept_ignore < (Math.floor(new Date().valueOf()/1000))) {
		                                FV_AcceptGift();
		                            } else {
		                                NextRequest(1,aParams[1]);
		                            }
		
		                        } else if (aParams[300]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    } else if (Self.Action.indexOf('sendmats') != -1) {
		                        // actions[http://apps.facebook.com/onthefarm/sendmats.php?feature=BotanicalGarden&gift=glasssheet&receiverId=1347256718&ts=1272746389]
		                        //Send Gifts
		                        if (aParams[301]==2) {
		                            FV_SendGift();
		                        } else if (aParams[301]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    } else if (Self.Action.indexOf('stimulus') != -1) {
		                        //Claim Bonus
		                        if (aParams[304]==2) {
		                            FV_ClaimBonus();
		                        } else if (aParams[304]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    } else {
		                        //Joins
		
		                        if (aParams[303]==2) {
		                            FV_Join();
		                        } else if (aParams[303]==1) {
		                            FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                        }
		                    }
		                    break;
		                default:
		                    GM_log('Ignoring Other Request');
		
		                    if (aParams[400]==1) {
		                        FB_do(strBase,strReject+Self.Parms+'&post_form_id_source=AsyncRequest');
		                    } else {
		                        LogPush('Skipping Other Request');
		                        NextRequest(1,aParams[1]);
		                    }
		                    break;
		            }
		
		            break;
		        case 'MWMessage':
		            switch (aCat[1]) {
		                case '3012':
		                    MW_AcceptGift();
		                    break;
		                case '3018':
		                    MW_SendGift();
		                    break;
		                case '3013':
		                    MW_Join();
		                    break;
		                default:
		                    NextRequest(1,aParams[1]);
		            }
		            break;
		        case 'FVMessage':
		            switch (aCat[1]) {
		                case '4':
		                    FV_AcceptGift();
		                    break;
		                case '6':
		                    FV_SendGift();
		                    break;
		                case '5':
		                    FV_Join();
		                    break;
		                default:
		                    NextRequest(1,aParams[1]);
		                }
		            break;
		    }
	    } else {
		    GM_log('Some one turn the switch off');
	    }
           
	}
}


/****  End Wall Notification code ****/

function StartProcessing() {
    LogPush('<span style="color:green"><strong>Starting Automatic Request processing</strong></span>');

    bAutoRun = true;
    iRequestNum = 0;
    FirstRequest = null;
    LastRequest = null;

    if (aParams[1] == null) aParams[1] = 0;
    if (aParams[3] == null) aParams[3] = 0;
    if (aParams[6] == null) aParams[6] = 0;


    if( aParams[1] > 0) {
        EventSpan.dispatchEvent(ActionRequest);
    } else {
        LogPush('Request Processing is Disabled');
    }
    if( aParams[3] > 0) {
        EventSpan.dispatchEvent(ActionWall);
    } else {
        LogPush('Wall Processing is Disabled');
    }
    if( aParams[6] > 0) {
	    GM_log('dispatching Event ActionRespect');
        EventSpan.dispatchEvent(ActionRespect);
    } else {
        LogPush('Respect Processing is Disabled');
    }

}

function StopProcessing() {

    bAutoRun = false;
    clearTimeout(iRespectCurrent);
    clearTimeout(iRequestCurrent);
    clearTimeout(iWallCurrent);
    LogPush('<span style="color:red"><strong>Stopping Automatic Request Processing</strong></span>');
}

/*** Start section to read in items from MW and FV	****/

//Read Respect
function ReadRespect() {

    var myUrl;
    var iHoldEvent, iWatchDog;
    
    iHoldEvent = iRespectCurrent;
    
    // stop processing if autorun turned off
    if (bAutoRun) {

	    oRespectList.First    = null;
	    oRespectList.Last     = null;
	
	    if (xw_sig_valid == false) {
		    GM_log('About Read Respect.  MW does not appear to be working');
            LogPush('<strong>Ignoring Crime Spree Gifts.  Mafia Wars does not appear to be working.  Checking again in '+aParams[6]+' minutes.</strong>');
            iRespectCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRespect);},getRandRange(aParams[6]*50000,aParams[6]*70000));
            if (iRespectCurrent < iHoldEvent) {
	            // The browser has reset.  Cancel runaway jobs;
	            clearTimeout(iRespectCurrent);
            }
	    } else {
 	  	    GM_log('start');
		    local_xw_sig = GM_getValue('local_xw_sig');
		    local_xw_user_id = GM_getValue('local_xw_user_id');
		
		    myUrl    =  'http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=safehouse&xw_action=view&xw_city=1&skip_req_frame=1'
		    myUrl   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
		
		    // start the WatchDog Timer to catch hung requests.  15 seconds maximum.
		    iWatchDog = setTimeout(function (e) {
		        iCurrentJob.abort();
		        GM_log('WatchDog timer killing Read Respect job.');
		
		        //zero out the found list
		        FirstRespect    = null;
		        LastRespect     = null;
		
		        LogPush('<strong>Finished processing crime spree gifts.  Checking again in '+aParams[6]+' minutes.</strong>');
		        iRespectCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRespect);},getRandRange(aParams[6]*50000,aParams[6]*70000));
                if (iRespectCurrent < iHoldEvent) {
		            // The browser has reset.  Cancel runaway jobs;
		            clearTimeout(iRespectCurrent);
	            }
		    }, 30000);
		
		    // check for respect
		    iCurrentJob = GM_xmlhttpRequest({
		        method: 'GET',
		        url:  myUrl,
		        headers: {
		            'Host':            'facebook.mafiawars.com',
		            'User-agent':       navigator.userAgent,
		            'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		            'Accept-Language': 'en-us,en;q=0.5',
		            'Accept-Encoding': 'gzip,deflate',
		            'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
		        },
		        onload: function(_responseDetails) {
		            try {
		
		                var strTemp;
		                var i1,i2;
		                var oDiv,oButton, oSnapShot;
		
		                var oRespect;
		
		                // clear watch dog timer
		                clearTimeout(iWatchDog);
		
		                if (_responseDetails.status != 200) {
		                    GM_log('Error checking for crime spree gifts');
		                } else {
		                    oDiv = document.createElement('div');
		
		                    strTemp = _responseDetails.responseText;
		
		                    i1 = strTemp.indexOf('<div class="gift_safehouse_giftbox_cont">');
		                    i2 = strTemp.indexOf('<script type="text/javascript">',i1);
		
		                    oDiv.innerHTML = strTemp.slice(i1,i2);
		
		                    //oSnapShot = getSnapshot('//div[@class="gift_safehouse_open_link"]/a',oDiv);
		                    oSnapShot = getSnapshot('//div[@class="gift_safehouse_open_link"]/a/span/span[text()="Open Safe!"]//parent::*//parent::a',oDiv);
		
		                    if(oSnapShot.snapshotLength>0) {
		                        LogPush('<strong>Found '+oSnapShot.snapshotLength+' crime spree gifts</strong>');
		
		                        for (var i=0;i<oSnapShot.snapshotLength;i++) {
		                            oButton         =   oSnapShot.snapshotItem(oSnapShot.snapshotLength-1-i);
		                            oRespect        =   new RespectItem();
		                            oRespect.Action	=   oButton.href;
		                            oRespectList.Append(oRespect);
		                        }
		                    }
		
		                    // start processing the requests
		
		                    if (oRespectList.First != null) {
		                         iRespectCurrent = setTimeout(function (e) {EventSpan.dispatchEvent(ActionRespect);}, getRandRange(aParams[5]*750,aParams[5]*1250));
		                    } else {
		                        LogPush('<strong>Finished processing crime spree gifts.  Checking again in '+aParams[6]+' minutes.</strong>');
		                        iRespectCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRespect);}, getRandRange(aParams[6]*50000,aParams[6]*70000));
		                    }
                            if (iRespectCurrent < iHoldEvent) {
					            // The browser has reset.  Cancel runaway jobs;
	            				clearTimeout(iRespectCurrent);
				            }

		               }
		            } catch(err) {
		                GM_log('Error: Read Respect - '+err.message);
		                LogPush('<strong>Error in Crime Spree Gifts.  Checking again in '+aParams[6]+' minutes.</strong>');
		                iRespectCurrent = setTimeout(function (e) { oRespectList.Erase(); EventSpan.dispatchEvent(ActionRespect);},getRandRange(aParams[6]*50000,aParams[6]*70000));
			            if (iRespectCurrent < iHoldEvent) {
				            // The browser has reset.  Cancel runaway jobs;
				            clearTimeout(iRespectCurrent);
			            }

		            }
		        }
		    });
	    }
    } else {
	    GM_log('Abort read request.  Switch is off');
    }
}

//Read Wall Posting
function ReadWall() {

    var myUrl;
    var iHoldEvent, iWatchDog;
    var iNewNow
    
    iHoldEvent = iWallCurrent;
    iNewNow = Math.floor(new Date().valueOf()/1000);
    
    // stop processing if autorun turned off
    if (bAutoRun) {

	    oRespectList.First    = null;
	    oRespectList.Last     = null;
	
	    myUrl           =   'http://www.facebook.com/ajax/intent.php?__a=1&newest='+iNow+'&dont_collapse=1&show_hidden=true&ignore_self=true&load_newer=true&request_type=4';
	
	    // start the WatchDog Timer to catch hung requests.  15 seconds maximum.
	    iWatchDog = setTimeout(function (e) {
	        iCurrentJob.abort();
	        GM_log('WatchDog timer killing Read Wall job.');
	        LogPush('<strong>Finished processing Wall Notices.  Checking again in '+aParams[3]+' seconds.</strong>');
	        iWallCurrent    = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);},getRandRange(aParams[3]*750,aParams[3]*1250));
	            if (iWallCurrent < iHoldEvent) {
	            // The browser has reset.  Cancel runaway jobs;
	            clearTimeout(iWallCurrent);
            }
	    }, 30000);
	
	    // check for wall notifications
	    iCurrentJob = GM_xmlhttpRequest({
	        method: 'GET',
	        url:  myUrl,
	        headers: {
	            'Host':            'www.facebook.com',
	            'User-agent':       navigator.userAgent,
	            'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	            'Accept-Language': 'en-us,en;q=0.5',
	            'Accept-Encoding': 'gzip,deflate',
	            'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
	            'X-SVN-Rev':        unsafeWindow.Env.svn_rev
	        },
	        onload: function(_responseDetails) {
	
	           try {
		            var i1, i2, iNumStories, iWallNum;
		            var strTemp, strHTML;
 	                var oDom, oDiv, oButton, oSnap;
		            var link_data;
		            var myImg;
	               
	                // clear watch dog timer
	                clearTimeout(iWatchDog);
	
	                strTemp = _responseDetails.responseText;
	
	                i1              = strTemp.indexOf('"num_stories":')
	                i2              = strTemp.indexOf(',',i1);
	                iNumStories     = strTemp.slice(i1+14,i2);
	                
	                iWallNum		= 0;
	
	                if (iNumStories > 0) {
	                    GM_log('Number of Stories Found = '+iNumStories);
	                    
	                    i1		= strTemp.indexOf('"newestStoryTime":')
	                    i2		= strTemp.indexOf(',"oldestSt',i1);
	                    
	                    iNow = strTemp.slice(i1+18,i2);
						
	                    i1      = strTemp.indexOf('"html":"')
	                    i2      = strTemp.indexOf('","',i1);
	                    
	                    oDom = document.createElement('div');
	                    oDom.innerHTML = eval('"'+strTemp.slice(i1+8,i2) +'"');
	                    
	                    for (var i=0;i<oDom.childNodes.length;i++){
	                        oDiv = oDom.childNodes[i]
	                        
	                        link_data = oDiv.getAttribute('data-ft');
	                        if (link_data != null) {
	                            eval('link_data = '+link_data);
	                            
	                            oDiv.id = "Ignore";
	                            switch (link_data.app_id) {
	
	                                case '10979261223':         // Mafia Wars
	                                case '102452128776':        // FarmVille
	
	                                    oSnap       = getSnapshot('.//div[@class="uiStreamAttachments mvm"]/div/a/img',oDiv)
	                                    if (oSnap.snapshotLength == 0) {
	                                        myImg = ""
	                                    } else {
	                                        myImg = oSnap.snapshotItem(0).src
	                                    }
	
	                                    //strMessage    = oSnap.textContent
								        oButton     = getSnapshot('.//span[@class="UIActionLinks UIActionLinks_bottom"]/a',oDiv).snapshotItem(0);
	
	                                    for (var name in Wall_Data[link_data.app_id]) {
	
	                                        if( (Wall_Data[link_data.app_id][name]['testURL'].test(oButton.href)) && (Wall_Data[link_data.app_id][name]['testIMG'].test(myImg))){
	
	                                            oWall           =   new WallItem();
	                                            
	                                            oWall.Type      =   name
	                                            oWall.Action	    =   oButton.href;
	                                            oWall.AppId     =   link_data.app_id;
	                                            oWall.srcImg    =   myImg;
	                                            if (name != "MW_WarHelp") {
	                                                //add to bottom
	                                                oWallList.Append(oWall);
                                            	} else {
	                                                //add to top
	                                                oWallList.Insert(oWall);
                                                }
	                                            GM_log('iWallNum = '+iWallNum);
	                                            iWallNum        =   iWallNum + 1;
   	                                            break;
	                                        }
	                                    }
	                                    break;
	                                case 'AppsIdforTestinggoeshere':
										// Testings Area
	
	                                    oSnap       = getSnapshot('.//div[@class="uiStreamAttachments mvm"]/div/a/img',oDiv)
	                                    if (oSnap.snapshotLength == 0) {
	                                        myImg = ""
	                                    } else {
	                                        myImg = oSnap.snapshotItem(0).src
	                                    }
	
	                                    //strMessage    = oSnap.textContent
	
	                                    oButton     = getSnapshot('.//span[@class="UIActionLinks UIActionLinks_bottom"]/a',oDiv).snapshotItem(0);
	
	                                    LogPush('oButton.href = '+oButton.href);
	                                    LogPush('oButton.textContent = '+oButton.textContent);
	                                    LogPush('myImg = '+myImg);
	
	                                    break;
	
	                                default:
	
	                            }
	
	                        } else {
		                        GM_log('link data is null');
	                        }
	                    }
	                } else {
	                    // found nothing
	                }
	                
	                if (oWallList.First != null) {
		                LogPush('<strong>'+iWallNum +' wall notification(s) have been found and will be processed</strong>');
                        iWallCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);}, getRandRange(aParams[2]*750,aParams[2]*1250));
                    } else {
                        iWallCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);}, getRandRange(aParams[3]*750,aParams[3]*1250));
                    }
                    if (iWallCurrent < iHoldEvent) {
			            // The browser has reset.  Cancel runaway jobs;
        				clearTimeout(iWallCurrent);
		            }
	            } catch(err) {
	                GM_log('Error: Read Respect - '+err.message);
	                LogPush('<strong>Error Reading Wall Notices.  Checking again in '+aParams[3]+' seconds.</strong>');
	                iWallCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionWall);}, getRandRange(aParams[3]*750,aParams[3]*1250));
                    if (iRespectCurrent < iHoldEvent) {
			            // The browser has reset.  Cancel runaway jobs;
        				clearTimeout(iRespectCurrent);
		            }
	            }
	        }
    	})
    } else {
	    GM_log('Abort read request.  Switch is off');
    }
}


// Read Request from MW, FV, and FB

function Read_MW_Requests(){

    var iCurrentJob;
    var iHoldEvent, iWatchDog;
    var myUrl;

    GM_log('Read_MW_Requests')

    local_xw_sig         =   GM_getValue('local_xw_sig');
    
	iRequestNum = 0;

    // exit this step if not needed.
    if (aParams[200]==0 && aParams[201]==0 && aParams[203]==0) {
        GM_log('skipping Read_MW_Requests');
        Read_FV_Requests();
    } else if (xw_sig_valid == false) {
        LogPush('<strong>Skipping Mafia Wars Messages.  Mafia Wars does not appear to be working.</strong>');
        Read_FV_Requests();
    } else {

        // start the WatchDog Timer to catch hung requests.  15 seconds maximum.
        iWatchDog = setTimeout(function (e) {
            iCurrentJob.abort();
            GM_log('WatchDog timer killing Read_MW_Requests');

            Read_FV_Requests();

        }, 30000);

        local_xw_sig = GM_getValue('local_xw_sig');
        local_xw_user_id = GM_getValue('local_xw_user_id');

        myUrl    =   'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/message_center.php?';
        myUrl   +=   '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;

        iCurrentJob = GM_xmlhttpRequest({
            method: 'GET',
            url:  myUrl,
            headers: {
                'Host':            'facebook.mafiawars.com',
                'User-agent':       navigator.userAgent,
                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-us,en;q=0.5',
                'Accept-Encoding': 'gzip,deflate',
                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
            },
            onload: function(_responseDetails) {
                try {
                    var i1,i2,i3, myUrl, myUrl2;
                    var strTemp, strTemp2;
                    var iType;

                    clearTimeout(iWatchDog);
                    iErrorCount = 0;

                    local_xw_sig = GM_getValue('local_xw_sig');
                    local_xw_user_id = GM_getValue('local_xw_user_id');


                    if (_responseDetails.status != 200) {
                        GM_log('Error Read message from MW page');
                    } else {

                        strTemp     = _responseDetails.responseText
                        strTemp     = strTemp.split('<div id="event_container_');

                        for( var i=1; i < strTemp.length; i++) {
                            i1      = 0
                            i2      = strTemp[i].indexOf('"');
                            iType   = strTemp[i].slice(0,i2);

                            do {
                                i1 = strTemp[i].indexOf('<div class="event" style="display: block;',i1)
                                if (i1!=-1) {
                                    oRequest            = new RequestItem();
                                    oRequest.Gifttype   = 'MWMessage_'+iType;

                                    i1 = i1 + 1;
                                    i2 = strTemp[i].indexOf("'accept', '",i1)+11;
                                    i3 = strTemp[i].indexOf("'",i2);

                                    switch (iType) {
                                        case "3012":
                                            if (aParams[200] == 2) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=accept';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[200] == 1) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=ignore';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                            break;
                                        case "3018":
                                            if (aParams[201] == 2) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=accept';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[201] == 1) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=ignore';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                            break;
                                        case "3013":
                                            if (aParams[203] == 2) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=accept';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[203] == 1) {
                                                oRequest.Action    =  'http://facebook.mafiawars.com/mwfb/remote/views/include/zmc_endpoints/callback.php?&action=ignore';
                                                oRequest.Action   +=  '&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.Action   +=  '&sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig;
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                    }

                                }
                            } while (i1!=-1)
                        }
                    }

                    GM_log('MW Request Read = '+iRequestNum);
                    Read_FV_Requests();

                } catch(err) {
                    GM_log('MW Request Read = '+iRequestNum);
                    GM_log('Error: Read MW Requests - '+err.message);
                    Read_FV_Requests();
                }
            }
        });
    }

}

function Read_FV_Requests(){

    var iHoldEvent, iCurrentJob;
    var iWatchDog;

    var myUrl;

    GM_log('Read_FV_Requests')

    // exit this step if not needed.
    if (aParams[300]==0 && aParams[301]==0 && aParams[303]==0) {
        GM_log('skipping Read_FV_Requests');
        Read_FB_Requests();
    } else {

        // start the WatchDog Timer to catch hung requests.  15 seconds maximum.
        iWatchDog = setTimeout(function (e) {
            iCurrentJob.abort();
            GM_log('WatchDog timer killing Read_FV_Requests');

            Read_FB_Requests();

        }, 30000);

        myUrl    =   'http://www.farmville.com/message_center.php';

        iCurrentJob = GM_xmlhttpRequest({
            method: 'GET',
            url:  myUrl,
            headers: {
                'Host':            'www.farmville.com',
                'User-agent':       navigator.userAgent,
                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-us,en;q=0.5',
                'Accept-Encoding': 'gzip,deflate',
                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
            },
            onload: function(_responseDetails) {
                try {
                    var i1,i2,i3, myUrl, myUrl2;
                    var strTemp, strTemp2;
                    var iType;

                    clearTimeout(iWatchDog);
                    iErrorCount = 0;

                    if (_responseDetails.status != 200) {
                        GM_log('Error Read message from MW page');
                    } else {

                        strTemp = _responseDetails.responseText;
                        strTemp     = strTemp.split('<div id="event_container_');

                        for( var i=1; i < strTemp.length; i++) {
                            i1      = 0
                            i2      = strTemp[i].indexOf('"');
                            iType   = strTemp[i].slice(0,i2);


                            do {

                                i1 = strTemp[i].indexOf('<div class="event" style="display: block;',i1)

                                if (i1!=-1) {
                                    oRequest            = new RequestItem();
                                    oRequest.Gifttype   = 'FVMessage_'+iType;

                                    i1 = i1 + 1;
                                    GM_log('id = 10979261223');
                                    i2 = strTemp[i].indexOf("'accept', '",i1)+11;
                                    i3 = strTemp[i].indexOf("'",i2);


                                    switch (iType) {
                                        case "4":
                                            if (aParams[300] == 2) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=accept&eventId='+strTemp[i].slice(i2,i3);
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[300] == 1) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=ignore&eventId='+strTemp[i].slice(i2,i3);
                                                oRequest.AddNode();
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                            break;
                                        case "6":
                                            if (aParams[301] == 2) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=accept&eventId='+strTemp[i].slice(i2,i3);
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[301] == 1) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=ignore&eventId='+strTemp[i].slice(i2,i3);
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                            break;
                                        case "5":
                                            if (aParams[303] == 2) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=accept&eventId='+strTemp[i].slice(i2,i3);
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            } else if (aParams[303] == 1) {
                                                oRequest.Action   =   'http://www.farmville.com/callback.php?&action=ignore&eventId='+strTemp[i].slice(i2,i3);
                                                oRequestList.Append(oRequest);
                                                iRequestNum                 =   iRequestNum + 1;
                                            }
                                    }

                                }
                            } while (i1!=-1)
                        }
                    }
                    
                    GM_log('FV Request Read = '+iRequestNum);
                    Read_FB_Requests();
                } catch(err) {
	                GM_log('FV Request Read = '+iRequestNum);
                    GM_log('Error: Read FV Requests - '+err.message);
                    Read_FB_Requests();
                }
            }
        });
    }

}

function Read_FB_Requests(){

    var iHoldEvent, iCurrentJob;
    var iWatchDog;

    var myUrl;
    
    iHoldEvent = iRequestCurrent;

    local_xw_sig         =   GM_getValue('local_xw_sig');

    GM_log('Read_FB_Requests');

    // start the WatchDog Timer to catch hung requests.  15 seconds maximum.
    iWatchDog = setTimeout(function (e) {
        iCurrentJob.abort();
        GM_log('WatchDog timer killing Read_FB_Requests');

        if (oRequestList.First != null) {
            LogPush('<strong>'+iRequestNum +' request(s) have been found and will be processed</strong>');
            iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[0]*750,aParams[0]*1250));
        } else {
            iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[1]*750,aParams[1]*1250));
        }
        if (iWallCurrent < iHoldEvent) {
            // The browser has reset.  Cancel runaway jobs;
			clearTimeout(iRequestCurrent);
		}

    }, 30000);

    myUrl    =   'http://www.facebook.com/reqs.php';

    iCurrentJob = GM_xmlhttpRequest({
        method: 'GET',
        url:  myUrl,
        headers: {
            'Host':            'www.facebook.com',
            'User-agent':       navigator.userAgent,
            'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-us,en;q=0.5',
            'Accept-Encoding': 'gzip,deflate',
            'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
            'Content-Type':    'application/x-www-form-urlencoded; charset=UTF-8'
        },
        onload: function(_responseDetails) {
            try {
                var i1,i2, myUrl, myUrl2;
                var oDOM, oForms, oForm, oFormInputs, oFormInput, oInputs, oInput, oRequest;
                var oSpan;
                var strTemp, strTempGift;
                var iButtons;
                var aCat;

                clearTimeout(iWatchDog);

                if (_responseDetails.status != 200) {
                    GM_log('Error Read message from MW page');
                } else {

                    strTemp = _responseDetails.responseText

                    i1 = strTemp.indexOf('<div class="UITwoColumnLayout_Container');
                    if (i1 == -1) {
                        GM_log('no Request have been found');
                        return
                    } else {

                        i2 = strTemp.indexOf('<div class="UITwoColumnLayout_NarrowContent',i1);
                        oDOM = document.createElement('div');
                        oDOM.innerHTML = strTemp.slice(i1,i2);

                        // find all the requests
                        oForms = getSnapshot(strConfirmBoxes, oDOM);

                        //GM_log('oForms.snapshotLength = '+oForms.snapshotLength );

                        for(i=0; i < oForms.snapshotLength; i++) {

                            oForm       =   oForms.snapshotItem(i);
                            aCat        =   oForm.id.split('_');

                            //GM_log('aCat[0] = '+ aCat[0] + ' aCat[1] = '+ aCat[1] );

                            switch (aCat[0]) {
                                case 'friend':
                                    switch (aCat[1]) {
                                        case 'suggestion':
                                            if (aParams[100]>0) {
                                                oFormInputs =   getSnapshot(strFormInputs1, oForm);
                                                for ( j=0; j<oFormInputs.snapshotLength; j++) {

                                                    oFormInput          =   oFormInputs.snapshotItem(j);
                                                    oInputs             =   getSnapshot(strInput,oFormInput);
                                                    oRequest            =   new RequestItem();
                                                    oRequest.Gifttype   = oForm.id;

                                                    for ( k=0; k < oInputs.snapshotLength; k++) {
                                                        oInput      =   oInputs.snapshotItem(k);
                                                        switch (oInput.type) {
                                                            case 'hidden':
                                                                // grab the parameters need to action the item
                                                                if (oInput.name != 'params[lists]') oRequest.Parms += "&"+oInput.name+"="+oInput.value;
                                                                break;
                                                           case 'submit':
                                                                // grab the name of what we are actioning, and the http action request
                                                                if (oInput.name.match(/actions\[reject\]/i) != null) {
                                                                    oRequest.Reject     = /actions\[([^\]]+)\]/.exec(oInput.name)[1];
                                                                } else {
                                                                    oRequest.Giftname   = oInput.value.trim();
                                                                    oRequest.Action       = /actions\[([^\]]+)\]/.exec(oInput.name)[1]
                                                                }
                                                        }
                                                    }

                                                    oRequest.Parms += '';

                                                    oRequest.Giftname           = oRequest.Giftname.replace('!','');
                                                    oRequestList.Append(oRequest);
                                                    iRequestNum                 =   iRequestNum + 1;
                                                }
                                            } else {
                                                GM_log('Skipping Friend Suggestion');
                                            }
                                            break;

                                        case 'connect':
                                            if (aParams[102]>0) {
                                                oFormInputs =   getSnapshot(strFormInputs1, oForm);
                                                for ( j=0; j<oFormInputs.snapshotLength; j++) {

                                                    oFormInput          =   oFormInputs.snapshotItem(j);
                                                    oInputs             =   getSnapshot(strInput,oFormInput);
                                                    oRequest            =   new RequestItem();
                                                    oRequest.Gifttype   = oForm.id;

                                                    for ( k=0; k < oInputs.snapshotLength; k++) {
                                                        oInput      =   oInputs.snapshotItem(k);
                                                        switch (oInput.type) {
                                                            case 'hidden':
                                                                // grab the parameters need to action the item
                                                                if (oInput.name != 'params[lists]') oRequest.Parms += "&"+oInput.name+"="+oInput.value;
                                                                break;
                                                           case 'submit':
                                                                // grab the name of what we are actioning, and the http action request
                                                                if (oInput.name.match(/actions\[reject\]/i) != null) {
                                                                    oRequest.Reject     = /actions\[([^\]]+)\]/.exec(oInput.name)[1];
                                                                } else {
                                                                    oRequest.Giftname   = oInput.value.trim();
                                                                    oRequest.Action       = /actions\[([^\]]+)\]/.exec(oInput.name)[1]
                                                                }
                                                        }
                                                    }

                                                    //GM_log('oRequest.Action = '+oRequest.Action);

                                                    oRequest.Parms += '';

                                                    oRequest.Giftname           = oRequest.Giftname.replace('!','');
                                                    oRequestList.Append(oRequest);
                                                    iRequestNum                 =   iRequestNum + 1;
                                                }
                                            } else {
                                                   GM_log('Skipping Friend Request');
                                            }

                                            break;
                                        }
                                        break;
                                        // End Friend

                                case 'event':
                                    if (aParams[104]>0) {
                                        oFormInputs =   getSnapshot(strFormInputs1, oForm);
                                        for ( j=0; j<oFormInputs.snapshotLength; j++) {

                                            oFormInput      =   oFormInputs.snapshotItem(j);
                                            oInputs         =   getSnapshot(strEvent,oFormInput);
                                            oRequest        =   new RequestItem();
                                            oRequest.Gifttype   = oForm.id;

                                            oRequest.Parms  =   '&ok=Okay&__d=1&action=remove';

                                            for ( k=0; k < oInputs.snapshotLength; k++) {
                                                oInput      =   oInputs.snapshotItem(k);
                                                if (oInput.type == 'hidden') {
                                                    switch (oInput.name) {
                                                        case 'id':oRequest.Parms += "&"+oInput.name+"="+oInput.value; break;
                                                        case 'type':oRequest.Parms += "&"+oInput.name+"="+oInput.value; break;
                                                        case 'status_div_id':oRequest.Parms += "&"+oInput.name+"="+oInput.value; break;
                                                        case 'post_form_id':oRequest.Parms += "&"+oInput.name+"="+oInput.value; break;
                                                        case 'fb_dtsg':oRequest.Parms += "&"+oInput.name+"="+oInput.value; break;
                                                    }
                                                }
                                            }

                                            //GM_log('oRequest.Parms = '+oRequest.Parms);

                                            oRequestList.Append(oRequest);
                                            iRequestNum                 =   iRequestNum + 1;
                                        }
                                    } else {
                                        GM_log('Skipping Event');
                                    }

                                    break;
                                    //End Event

                                case 'group':
                                case 'cause':
                                case 'fbpage':
                                case 'confirm':

                                    oFormInputs =   getSnapshot(strFormInputs, oForm);

                                    GM_log('oFormInputs.snapshotLength = '+oFormInputs.snapshotLength);


                                    for ( j=0; j<oFormInputs.snapshotLength; j++) {

                                        oFormInput      =   oFormInputs.snapshotItem(j);
                                        oInputs         =   getSnapshot(strInput,oFormInput);

                                        oRequest    = new RequestItem();

                                        oRequest.Gifttype   = oFormInput.parentNode.id;
                                        //GM_log(oRequest.Gifttype);

                                        iButtons = 0;

                                        for ( k=0; k < oInputs.snapshotLength; k++) {
                                            oInput      =   oInputs.snapshotItem(k);
                                            switch (oInput.type) {
                                                case 'hidden':
                                                    // grab the parameters need to action the item
                                                    if(oInput.name == 'charset_test')
                                                        oRequest.Parms += "&"+oInput.name+"=%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84"
                                                    else
                                                        oRequest.Parms += "&"+oInput.name+"="+oInput.value;
                                                    break;
                                                case 'submit':
                                                    // grab the name of what we are actioning, and the http action request
                                                    iButtons += 1;
                                                    if (oInput.name.match(/actions\[reject\]/i) != null) {
                                                        oRequest.Reject     = /actions\[([^\]]+)\]/.exec(oInput.name)[1];
                                                    } else {
                                                        oRequest.Giftname   = oInput.value;
                                                        oRequest.Action       = "&"+codeStrings(oInput.name)+"="+codeStrings(oInput.value);
                                                    }
                                            }
                                        }

                                        oRequest.Parms += '';

                                        if (iButtons<2) {
                                            GM_log('Ignoring malformed gift request. (no Accept button)');
                                            oRequest = undefined;
                                        } else if (aCat[0]=='fbpage' ) {
                                            if (aParams[105]==0 ) {
                                                GM_log('Skipping Group Invitation');
                                            } else {
                                                oRequestList.Append(oRequest);
                                                iRequestNum =   iRequestNum + 1;
                                            }
                                        } else if (aCat[0]=='group' ) {
                                            if (aParams[106]==0 ) {
                                                GM_log('Skipping Group Invitation');
                                            } else {
                                                oRequestList.Append(oRequest);
                                                iRequestNum =   iRequestNum + 1;
                                            }
                                        } else if (aCat[0] == 'confirm' ) {
                                            GM_log('Mafia Wars Request');
                                            if (aCat[1] == '10979261223') {
                                                if (oRequest.Action.indexOf('accept_gift') != -1 ) {
                                                    if (aParams[200]==0) {
                                                        GM_log('Skipping Mafia Wars Accept Gift Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                } else if (oRequest.Action.indexOf('answer_gift') != -1 ) {
                                                    if (aParams[201]==0) {
                                                        GM_log('Skipping Mafia Wars Send Gift Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                } else if (oRequest.Action.indexOf('recruit') != -1 ) {
                                                    if (aParams[203]==0) {
                                                        GM_log('Skipping Mafia Wars Join Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                }
                                            } else if (aCat[1] == '102452128776') {

                                                if (oRequest.Action.indexOf('giftaccept') != -1 ) {
                                                   if ( aParams[300]==0) {
                                                        GM_log('Skipping FarmVille Accept Gift Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                } else if (oRequest.Action.indexOf('sendmats') != -1 ) {
                                                    GM_log('found sendmats');
                                                    if ( aParams[301]==0) {
                                                        GM_log('Skipping FarmVille Send Gift Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                } else if (oRequest.Action.indexOf('stimulus') != -1 ) {
                                                    if ( aParams[304]==0) {
                                                        GM_log('Skipping FarmVille Claim Bonus Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                } else if (oRequest.Action.indexOf('addneighbor') != -1 ) {
                                                    if (aParams[303]==0) {
                                                        GM_log('Skipping FarmVille Join Request');
                                                    } else {
                                                        oRequestList.Append(oRequest);
                                                        iRequestNum =   iRequestNum + 1;
                                                    }
                                                }
                                            } else {
                                                if (aParams[400]==0) {
                                                    GM_log('Skipping Other Request');
                                                } else {
                                                    oRequestList.Append(oRequest);
                                                    iRequestNum =   iRequestNum + 1;
                                                }
                                            }
                                        }

                                    }
                                    break;
                                    // End read in general postings
                                }
                                // End Switch
                        }
                        // end loop

                    }

                    GM_log('done: ' +iRequestNum);

                    if (oRequestList.First != null) {
		                LogPush('<strong>'+iRequestNum +' request(s) have been found and will be processed</strong>');
		                iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[0]*750,aParams[0]*1250));
                    } else {
		                iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[1]*750,aParams[1]*1250));
                    }
                    if (iRequestCurrent < iHoldEvent) {
			            // The browser has reset.  Cancel runaway jobs;
		                GM_log('test4');
        				clearTimeout(iRequestCurrent);
    				}

                }
            } catch(err) {
	            GM_log('Error done: ' +iRequestNum);
                GM_log('Error: Read FB Requests - '+err.message);
                if (oRequestList.First != null) {
	                LogPush('<strong>'+iRequestNum +' request(s) have been found and will be processed</strong>');
                    iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[0]*750,aParams[0]*1250));
                } else {
                    iRequestCurrent = setTimeout(function (e) { EventSpan.dispatchEvent(ActionRequest);}, getRandRange(aParams[1]*750,aParams[1]*1250));
                }
                if (iWallCurrent < iHoldEvent) {
		            // The browser has reset.  Cancel runaway jobs;
    				clearTimeout(iRequestCurrent);
				}
            }

        }
    });
}







/****  Initialization Routine  ****/

function Initialize() {

    var oDom, oDiv, oButton, oText;

    var strGMList,strPara;
    var aTempPara = new Array();
    
    //Case Specific Initialization
    switch (strFrameId) {
        case 'MafiaWars':

            // get a current xw_sig if Mafia Wars is open
            MW_xw_sig_update();

            break;

        case 'FaceBook':
        
    	    // create lists
			oRespectList	= new List(ReadRespect);
			oWallList		= new List(ReadWall);
			oRequestList	= new List(Read_MW_Requests);

        	// Set up Event handling
        	EventSpan = document.createElement('span');

        	EventSpan.addEventListener("FBAA-ActionRespect",	function(evt) {oRespectList.Run()}, false);
			EventSpan.addEventListener("FBAA-ActionWall",		function(evt) {oWallList.Run()}, false);
			EventSpan.addEventListener("FBAA-ActionRequest",	function(evt) {oRequestList.Run()}, false);
			
			ActionRespect	= document.createEvent("Events"); ActionRespect.initEvent("FBAA-ActionRespect", false, false); 
			ActionWall		= document.createEvent("Events"); ActionWall.initEvent("FBAA-ActionWall", false, false); 
			ActionRequest	= document.createEvent("Events"); ActionRequest.initEvent("FBAA-ActionRequest", false, false); 
			
            //set Up Log File

            oLogDiv = document.createElement('div');
            oLogDiv.setAttribute('style',"width: 770px; height: 250px; overflow: auto; border: 1px solid rgb(204, 204, 204);padding-bottom: 2px;");

            oLogDiv.innerHTML = GM_getValue('LogDiv','');
            GM_setValue('LogDiv',oLogDiv.innerHTML);

            //set the time for wall processing
            iNow = Math.floor(new Date().valueOf()/1000)-60*5;

            //set up the FV Delay timer
            FV_accept_ignore = 0;

            // fb user id
            if(unsafeWindow.self.Env.user == undefined)
                FB_user_id = GM_getvalue('FB_user_id',0)
            else
                FB_user_id = unsafeWindow.self.Env.user;
            GM_setValue('FB_user_id',FB_user_id+'');
            GM_log('FB_user_id = '+FB_user_id);

            //set up the group Names
            strGroups       =   '<option value="0">-</option>';
            getGroupNames();

            // start a routine to keep the xw_sig current
            xw_sig_valid = false;
            FB_xw_sig_update();

            bAutoRun    = GM_getValue('bAutoRun',false);
            bShowLog    = GM_getValue('bShowLog',false);

            //read running parameters
            for (var i=0;i<5;i++) {
                switch (i) {
                    case 0:
                        // General
                        strPara = GM_getValue('FBAA-Form'+i,'5;30;5;10;100;5;30');
                        GM_setValue('FBAA-Form'+i,strPara);
                        break;
                    case 1:
                        //FaceBook
                        strPara = GM_getValue('FBAA-Form'+i,'0;0;0;0;0;0');
                        GM_setValue('FBAA-Form'+i,strPara);
                        break;
                    case 2:
                        // Mafia Wars
                        strPara = GM_getValue('FBAA-Form'+i,'0;0;1;0;false;false;false;false;false;false;false;false;false;false;false;false;false;false');
                        GM_setValue('FBAA-Form'+i,strPara);
                        break;
                    case 3:
                        // Farmville
                        strPara = GM_getValue('FBAA-Form'+i,'0;0;1;0;0;1;false;false;false;false;false;false;false;false;false;false;false;false;false');
                        if (strPara.length<20)
                            strPara += ';false;false;false;false;false;false;false;false;false;false;false;false;false';
                        GM_setValue('FBAA-Form'+i,strPara);
                        break;
                    case 4:
                        // Others
                        strPara = GM_getValue('FBAA-Form'+i,'0');
                        GM_setValue('FBAA-Form'+i,strPara);
                        break;

                }
                //GM_log('FBAA-Form['+i+']= '+strPara);
                aTempPara = strPara.split(';');
                for (var j=0;j<aTempPara.length;j++)

                    if (aTempPara[j]=='true')
                        aParams[i*100+j] = true
                    else if (aTempPara[j]=='false')
                        aParams[i*100+j] = false
                    else
                        aParams[i*100+j] = aTempPara[j];
            }

            GM_setValue('bAutoRun',bAutoRun);
            GM_getValue('bShowLog',bShowLog);

            if (bAutoRun) iRequestCurrent = setTimeout(function (e) { StartProcessing();}, 15000)

            //setup display
            createDisplay();

            break;
    }
}

/**** Create Auto Accept Display  ****/
function createDisplay() {

    var oDom;
    var oDiv, oDiv1, oDiv2, oTable, oTr, oTh, oTd, oForm, oInput, oImg, oH, oP, oUl;
    var oHeader;

    oDom = document.getElementById('contentCol');

    if ((oDom !=null) && (document.getElementById(strFBAutoAccept)==null)) {
        GM_log('create Display');
        oHeader = document.createElement('div');
        oHeader.setAttribute('style','padding-left: 15px; padding-right: 15px;');
        oHeader.id = strFBAutoAccept;
        oDom.insertBefore(oHeader,oDom.firstChild);

        // create Title
        oDiv = document.createElement('div');
        oDiv.setAttribute('class',"uiHeader uiHeader uiHeaderPage ptm pbl");
            oDiv1 = document.createElement('div');
            oDiv1.setAttribute('class',"clearfix uiHeaderTop");
            oDiv1.setAttribute('style','height: 10px;');
                oDiv2 = document.createElement('div');
                oDiv2.setAttribute('class',"lfloat");
                    oH = document.createElement('h2');
                    oH.setAttribute('class',"uiHeaderTitle");
                        oImg = document.createElement('img');
                        oImg.setAttribute('height','18px');
                        oImg.src = imgLogo;
                    oH.appendChild(oImg);
                    oH.appendChild(document.createTextNode("  Mafia Wars and FarmVille Request Processor"));
                oDiv2.appendChild(oH);
            oDiv1.appendChild(oDiv2);
        oDiv.appendChild(oDiv1);
        oHeader.appendChild(oDiv);

        //Create Buttons for Header
        oDiv = document.createElement('div');
        oDiv.setAttribute('style',"border-bottom: 1px solid rgb(204, 204, 204); padding-bottom:2px");
            oTable = document.createElement('table');
                oTbody = document.createElement('tbody');
                    oTr = document.createElement('tr');
                        oTd = document.createElement('td');
                        oTd.setAttribute('width',"200px");
                            oFont = document.createElement('font');
                            oFont.setAttribute('style',"color: rgb(0, 0, 0); font-size: 13px; font-weight: normal;");
                            oFont.appendChild(document.createTextNode("Auto Process: "));
                                oSpan = document.createElement('span');
                                oSpan.id = strAutoOn;
                                oSpan.addEventListener("click", click_AutoRun(1), false);
                                if (bAutoRun)
                                    oSpan.innerHTML= '<b>On</b>'
                                else
                                    oSpan.innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>On</a> </font>';
                            oFont.appendChild(oSpan);
                            oFont.appendChild(document.createTextNode(" / "));
                                oSpan = document.createElement('span');
                                oSpan.id = strAutoOff;
                                oSpan.addEventListener("click", click_AutoRun(0), false);
                                if (!bAutoRun)
                                    oSpan.innerHTML= '<b>Off</b>'
                                else
                                    oSpan.innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Off</a> </font>';

                            oFont.appendChild(oSpan);
                        oTd.appendChild(oFont);
                    oTr.appendChild(oTd);
                        oTd = document.createElement('td');
                        oTd.setAttribute('width',"200px");
                            oFont = document.createElement('font');
                            oFont.setAttribute('style',"color: rgb(0, 0, 0); font-size: 13px; font-weight: normal;");
                            oFont.appendChild(document.createTextNode("Log: "));
                                oSpan = document.createElement('span');
                                oSpan.id = strLogShow;
                                oSpan.addEventListener("click", click_ShowLog(1), false);
                                if (bShowLog)
                                    oSpan.innerHTML= '<b>Show</b>'
                                else
                                    oSpan.innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Show</a> </font>';
                            oFont.appendChild(oSpan);
                            oFont.appendChild(document.createTextNode(" / "));
                                oSpan = document.createElement('span');
                                oSpan.id = strLogHide;
                                oSpan.addEventListener("click", click_ShowLog(0), false);
                                if (!bShowLog)
                                    oSpan.innerHTML= '<b>Hide</b>'
                                else
                                    oSpan.innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Hide</a> </font>';
                            oFont.appendChild(oSpan);
                        oTd.appendChild(oFont);
                    oTr.appendChild(oTd);
                        oTd = document.createElement('td');
                        oTd.setAttribute('width',"120px");
                            oSpan = document.createElement('span');
                            oSpan.innerHTML = '<font style="color: rgb(59, 89, 152); font-size: 13px; font-weight: normal; cursor: pointer;"><a>Settings</a></font>';
                            oSpan.addEventListener("click",  click_ShowSetting, false);
                        oTd.appendChild(oSpan);
                    oTr.appendChild(oTd);
                        oTd = document.createElement('td');
                        oTd.setAttribute('width',"120px");
                            oSpan = document.createElement('span');
                            oSpan.innerHTML = '<font style="color: rgb(59, 89, 152); font-size: 13px; font-weight: normal; cursor: pointer;"><a>Check Updates</a></font>';
                            oSpan.addEventListener("click",  function() { updateCheck(true);}, false);
                        oTd.appendChild(oSpan);
                    oTr.appendChild(oTd);
                        oTd = document.createElement('td');
                            oFont = document.createElement('font');
                            oFont.setAttribute('style',"color: rgb(0, 0, 0); font-size: 13px; font-weight: normal;");
                            oFont.appendChild(document.createTextNode("Version: "+script_version));
                        oTd.appendChild(oFont);
                    oTr.appendChild(oTd);
                oTbody.appendChild(oTr);
            oTable.appendChild(oTbody);
        oDiv.appendChild(oTable);
        oHeader.appendChild(oDiv);


        // Add Settings Floating Window
        oDom = document.createElement('div');
        oDom.id = strFBAASettings;
        oDom.setAttribute('style',"display:none; -moz-border-radius: 10px; border: 5px solid rgb(104, 104, 104); padding: 5px; overflow: auto; margin-top: -30px; margin-left: 20px; background-color: white; width: 600px; height: 360px; position: absolute; z-index: 100;");
            oDiv = document.createElement('div');
                oTable = document.createElement('table');
                oTable.setAttribute('width','100%');
                //oTable.setAttribute('style','border-bottom:1px solid black');
                    oTbody = document.createElement('tbody');
                    	oTr = document.createElement('tr');
                    		oTh = document.createElement('th');
                    		oTh.innerHTML = '<div><h1 class="uiHeaderTitle">FBAA - Settings</h1></div>';
                    		oTh.setAttribute('style',"padding-bottom: 10px;");
                    		oTh.setAttribute('colspan',"2");
                    	oTr.appendChild(oTh);		
                    oTbody.appendChild(oTr);
                    	oTr = document.createElement('tr');
                    		oTh = document.createElement('th');
                    		oTh.innerHTML = 'Catagory';
                    		oTh.setAttribute('width',"110");
                    		oTh.setAttribute('Style',"border-bottom: 1px solid rgb(204, 204, 204)");
                    	oTr.appendChild(oTh);		
							oTh = document.createElement('th');
                    		oTh.innerHTML = 'Settings';
                    		oTh.setAttribute('Style',"border-bottom: 1px solid rgb(204, 204, 204)");
                    	oTr.appendChild(oTh);	
                    oTbody.appendChild(oTr);
                    	oTr = document.createElement('tr');
                    		oTd = document.createElement('td');
                    			oDiv1 = document.createElement('div');
                    			oDiv1.setAttribute('style','border: 0px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 110px; height: 280px;');
                    				oUl = document.createElement('ul');
                    				oUl.setAttribute('class',"uiSideNav");
                    				oUl.appendChild(addMenu("General",0));
                    				oUl.appendChild(addMenu("FaceBook", 1));
                    				oUl.appendChild(addMenu("Mafia Wars", 2));
                    				oUl.appendChild(addMenu("FarmVille", 3));
                    				oUl.appendChild(addMenu("Others", 4));
                    			oDiv1.appendChild(oUl);
                    		oTd.appendChild(oDiv1);
                    	oTr.appendChild(oTd);
                    		oTd = document.createElement('td');
                    			oTd.appendChild(CreateGeneralTab(0));
                    			oTd.appendChild(CreateFaceBookTab(1));
                    			oTd.appendChild(CreateMafiaWarsTab(2));
                    			oTd.appendChild(CreateFarmVilleTab(3));
                    			oTd.appendChild(CreateOtherTab(4));
                    			
                    			GM_log('oTd.innerHTML = '+oTd.innerHTML );
						oTr.appendChild(oTd);
                    oTbody.appendChild(oTr);
                oTable.appendChild(oTbody);
           oDiv.appendChild(oTable);
		oDom.appendChild(oDiv);
           oDiv = document.createElement('div');
                oTable = document.createElement('table');
                oTable.setAttribute('width','100%');
                    oTbody = document.createElement('tbody');
                        oTr = document.createElement('tr');
                            oTd = document.createElement('td');
                            oTd.setAttribute('width',"150");
						oTr.appendChild(oTd);
	                        oTd = document.createElement('td');
                            oTd.setAttribute('width',"220");
                            oTd.setAttribute('style','text-align:center');
                                oSpan = document.createElement('span');
                                oSpan.addEventListener("click", click_CloseSettings(0), false);

                                    oFont = document.createElement('font');
                                    oFont.setAttribute('style',' font-size: 13px; color: rgb(59, 89, 152); cursor: pointer;');
                                    oFont.innerHTML = '<a>Accept Changes</a>';
                                oSpan.appendChild(oFont);
                            oTd.appendChild(oSpan);
                        oTr.appendChild(oTd);
                            oTd = document.createElement('td');
                            oTd.setAttribute('style','text-align:center');
                                oSpan = document.createElement('span');
                                oSpan.addEventListener("click", click_CloseSettings(1), false);
                                    oFont = document.createElement('font');
                                    oFont.setAttribute('style',' font-size: 13px; color: rgb(59, 89, 152); cursor: pointer;');
                                    oFont.innerHTML = '<a>Cancel</a>';
                                oSpan.appendChild(oFont);
                            oTd.appendChild(oSpan);
                        oTr.appendChild(oTd);
                    oTbody.appendChild(oTr);
                oTable.appendChild(oTbody);
            oDiv.appendChild(oTable);
        oDom.appendChild(oDiv);
        oHeader.appendChild(oDom);



        //Create Log Window
        oDom = document.createElement('div');
        oDom.setAttribute('style','display: ;');
        oDom.id = strFBAALog;
            oP = document.createElement('p');
            oP.setAttribute('style',"text-align: right;");
                oFont = document.createElement('font');
                oFont.setAttribute('style',"color: rgb(59, 89, 152); font-size: 13px; font-weight: normal; cursor: pointer;");
                    oButton = document.createElement('a');
                    oButton.textContent = "Clear Log";
                    oButton.addEventListener("click", click_ClearLog, false);
                oFont.appendChild(oButton);
            oP.appendChild(oFont);
        oDom.appendChild(oP);
            oDiv = document.createElement('div');
            oDiv.setAttribute('style',"width: 770px; height: 250px; overflow: auto; border: 1px solid rgb(204, 204, 204);padding-bottom: 2px;");
        oDom.appendChild(oDiv);
        oHeader.appendChild(oDom);

        oDom.replaceChild(oLogDiv,oDiv);
        if (bShowLog)
            oLogDiv.parentNode.style.display = ""
        else
            oLogDiv.parentNode.style.display = "none"

    }

    function addMenu( _text, _index) {
        var oLi, oSpan, oImg, oButton, oTxt;

		oLi = document.createElement('li')
		oLi.setAttribute('id',strFBAASetTabs+_index);
		if (_index==0)
			oLi.setAttribute('class','selected')
		else
			oLi.setAttribute('class','');
			
			oButton = document.createElement('a');
			oButton.setAttribute('class','item');
				oSpan = document.createElement('span');
				oSpan.setAttribute('class','imgWrap');
					oImg = document.createElement('img');
					oImg.setAttribute('class','img');
					oImg.setAttribute('src',imgCatagory[_index]);
				oSpan.appendChild(oImg);
			oButton.appendChild(oSpan);
				oTxt = document.createTextNode(_text)
			oButton.appendChild(oTxt);
			oButton.addEventListener("click", click_ShowSettingsTab(_index), false);
		oLi.appendChild(oButton);			
		
        return oLi;
    }

    function createCheckBox(_oTr, _iPar,_strName) {
        var oTd, oInput, oText;

        oTd = document.createElement('td');
            oInput = document.createElement('input');
            oInput.name = "FBAA-Para-"+_iPar;
            oInput.type = "checkbox";
        oTd.appendChild(oInput);
            oText = document.createTextNode(_strName);
        oTd.appendChild(oText);
        _oTr.appendChild(oTd);
    }
    
    function createCheckBoxList(_oTr,_iPar, _strName) {
		var oUl, oLi, oTd, oInput, oText;
		var aNames;
		
		aName = _strName.split(',');
		
		oTd = document.createElement('td');
		oTd.setAttribute('colspan','3');
			oUl = document.createElement('ul');
			oUl.setAttribute('style','border: 1px solid rgb(204, 204, 204); height: 88px; list-style: none outside none; overflow: auto;');
			
			for (var i=0;i<aName.length;i++) {
					oLi = document.createElement('li');
						oInput = document.createElement('input');
				        oInput.name = "FBAA-Para-"+(_iPar+i);
				        oInput.type = "checkbox";
					oLi.appendChild(oInput);
						oText = document.createTextNode(aName[i]);
					oLi.appendChild(oText);
				oUl.appendChild(oLi);
			}
		    
		oTd.appendChild(oUl);
        _oTr.appendChild(oTd);
	    
    }

    function createDropDownList(_oTr, _iPar,_strName, _strOptions, _strValues) {
        var oTd, oSelect, oOption;
        var aOptions = new Array();
        var aValues = new Array();

        aOptions = _strOptions.split(';');
        aValues = _strValues.split(';');

        oTd = document.createElement('td');
        oTd.setAttribute('style',"width: 100px; text-align: right;");
        oTd.textContent = _strName+":";

        _oTr.appendChild(oTd);

        oTd = document.createElement('td');
        oTd.setAttribute('style',"width: 100px;");
            oSelect = document.createElement('select');
            oSelect.name = "FBAA-Para-"+_iPar;
            oSelect.setAttribute('style',"width: 100px;");
                for (var i=0;i<aOptions.length;i++) {
                    oOption = document.createElement('option');
                    oOption.value = aValues[i];
                    oOption.textContent = aOptions[i];
                    oSelect.appendChild(oOption);
                }
        oTd.appendChild(oSelect);
        _oTr.appendChild(oTd);
    }

    function CreateGeneralTab(_id) {
        var oDom, oForm, oTable, oTbody, oTr, oTh, oTd ;
        oDom = document.createElement('div');
        if (_id==0)
            oDom.setAttribute('style','display: ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;')
        else
            oDom.setAttribute('style','display:none ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;');

        oDom.id = strFBAASetDivs+_id;
			oForm = document.createElement('form');
	            oForm.name = 'FBAA-Form'+_id;
	
	            // create layout;
	            oTable = document.createElement('table');
	            oTable.setAttribute('width','100%');
	                oTbody = document.createElement('tbody');
	                	oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Request Timer";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 0,'Processing Interval','1 seconds;2 seconds;3 seconds;4 seconds;5 seconds;6 seconds;7 seconds;8 seconds;9 seconds;10 seconds','1;2;3;4;5;6;7;8;9;10');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 1,'Cycle Period','DISABLE; 1 minute;5 minutes;15 mintues;30 minutes;1 hour;3 hours;6 hours;12 hours;1 day','0;1;5;15;30;60;180;360;720;1440');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Wall Notification Timer";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 2,'Processing Interval','1 seconds;2 seconds;3 seconds;4 seconds;5 seconds;6 seconds;7 seconds;8 seconds;9 seconds;10 seconds','1;2;3;4;5;6;7;8;9;10');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 3,'Cycle Period','DISABLE;5 seconds;10 seconds;15 seconds;20 seconds;25 seconds;30 seconds','0;5;10;15;20;25;30');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Mafia Wars Crime Spree Timer";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 5,'Processing Interval','1 seconds;2 seconds;3 seconds;4 seconds;5 seconds;6 seconds;7 seconds;8 seconds;9 seconds;10 seconds','1;2;3;4;5;6;7;8;9;10');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 6,'Cycle Period','DISABLE; 1 minute;5 minutes;15 mintues;30 minutes;1 hour;3 hours;6 hours;12 hours;1 day','0;1;5;15;30;60;180;360;720;1440');
	                oTbody.appendChild(oTr);
		                oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Log Length";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 4,'Log Length','25 items; 50 items; 100 items; 150 items; 200 items; 400 items; 800 items; 1600 items; 3200 items','25;50;100;150;200;400;800;1600;3200');
	                oTbody.appendChild(oTr);
	            oTable.appendChild(oTbody)
	         oForm.appendChild(oTable)
	     oDom.appendChild(oForm);
	        
        return oDom;
	}
    
    function CreateFaceBookTab(_id) {
        var oDom, oForm, oTable, oTbody, oTr, oTh, oTd ;
        oDom = document.createElement('div');
        if (_id==0)
            oDom.setAttribute('style','display: ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;')
        else
            oDom.setAttribute('style','display:none ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;');

        oDom.id = strFBAASetDivs+_id;
			oForm = document.createElement('form');
	            oForm.name = 'FBAA-Form'+_id;
	
	            // create layout;
	            oTable = document.createElement('table');
	            oTable.setAttribute('width','100%');
	                oTbody = document.createElement('tbody');
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Friends";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 100,'Suggestions','Confirm;Ignore;Do Nothing','2;1;0');
	                        oTd = document.createElement('td');
	                        oTd.setAttribute('style',"width: 120px; text-align: right;");
	                        oTd.textContent = "Add to List:";
	                    oTr.appendChild(oTd);
	                        oTd = document.createElement('td');
	                        oTd.setAttribute('style',"width: 120px;");
	                            oSelect = document.createElement('select');
	                            oSelect.name = "FBAA-Para-101";
	                            oSelect.setAttribute('style',"width: 120px;");
	                            oSelect.innnerHTML = strGroups;
	                        oTd.appendChild(oSelect);
	                    oTr.appendChild(oTd);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 102,'Invitation','Confirm;Ignore;Do Nothing','2;1;0');
	                        oTd = document.createElement('td');
	                        oTd.setAttribute('style',"width: 120px; text-align: right;");
	                        oTd.textContent = "Add to List:";
	                    oTr.appendChild(oTd);
	                        oTd = document.createElement('td');
	                        oTd.setAttribute('style',"width: 120px;");
	                            oSelect = document.createElement('select');
	                            oSelect.name = "FBAA-Para-103";
	                            oSelect.setAttribute('style',"width: 120px;");
	                            oSelect.innnerHTML = strGroups;
	                        oTd.appendChild(oSelect);
	                    oTr.appendChild(oTd);
	                oTbody.appendChild(oTr);
	                        oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Other";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 104,'Event Invitations','Remove;Do Nothing','1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 105,'Page Suggestions','Ignore;Do Nothing','1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 106,'Group Invitations','Ignore;Do Nothing','1;0');
	                oTbody.appendChild(oTr);
	            oTable.appendChild(oTbody)
	         oForm.appendChild(oTable)
	     oDom.appendChild(oForm);
	        
        return oDom;
	}

    function CreateMafiaWarsTab(_id) {
        var oDom, oForm, oTable, oTbody, oTr, oTh, oTd ;
        oDom = document.createElement('div');
        if (_id==0)
            oDom.setAttribute('style','display: ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;')
        else
            oDom.setAttribute('style','display:none ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;');

        oDom.id = strFBAASetDivs+_id;
			oForm = document.createElement('form');
	            oForm.name = 'FBAA-Form'+_id;
	
	            // create layout;

	            oTable = document.createElement('table');
	            oTable.setAttribute('width','100%');
	                oTbody = document.createElement('tbody');
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Request Settings";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 200,'Accept Gifts','Confirm;Ignore;Do Nothing','2;1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 201,'Send Gifts','Confirm;Ignore;Do Nothing','2;1;0');
	                    createDropDownList(oTr, 202,'Reward','Experience;Energy;Stamina','1;2;3');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 203,'Join','Confirm;Ignore;Do Nothing','2;1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Wall Settings";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,204,"Help on Jobs");
	                    createCheckBox(oTr,205,"F. of Friend");
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,206,"Next Target");
	                    createCheckBox(oTr,207,"HitList Bounty");
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,208,"Bon-Loot-Rew");
	                    createCheckBox(oTr,209,"$$ Launder");
	                    createCheckBox(oTr,210,"Supply Parts");
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,211,"War Help");
	                    createCheckBox(oTr,212,"Betray");
	                oTbody.appendChild(oTr);
	
	            oTable.appendChild(oTbody);

            oForm.appendChild(oTable);
        oDom.appendChild(oForm);
        return oDom;
    };

    function CreateFarmVilleTab(_id) {
        var oDom, oForm, oTable, oTbody, oTr, oTh, oTd ;
        oDom = document.createElement('div');
        if (_id==0)
            oDom.setAttribute('style','display: ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;')
        else
            oDom.setAttribute('style','display:none ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;');

        oDom.id = strFBAASetDivs+_id;
			oForm = document.createElement('form');
	            oForm.name = 'FBAA-Form'+_id;
	
	            // create layout;
	            oTable = document.createElement('table');
	            oTable.setAttribute('width','100%');
	                oTbody = document.createElement('tbody');
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Request Settings";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 300,'Accept Gifts','Confirm;Ignore;Do Nothing','2;1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 301,'Send Gifts','Confirm;Ignore;Do Nothing','2;1;0');
	                    createDropDownList(oTr, 302,'Reward','No Reward','1');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 304,'Claim Bonus','Confirm;Ignore;Do Nothing','2;1;0');
	                    createDropDownList(oTr, 305,'Reward','10x Stable Parts;3x Puppy Kibble;10x Spring Eggs','1;2;3');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 303,'Join','Confirm;Ignore;Do Nothing','2;1;0');
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Wall Settings";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,304,"Barn Raising");
	                    createCheckBox(oTr,305,"Lend a Hand");
	                    createCheckBox(oTr,306,"Help Stallion");
	                    createCheckBox(oTr,307,"Bonus")
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,308,"Farmhands");
	                    createCheckBox(oTr,309,"Arborists");
	                    createCheckBox(oTr,310,"Bouquets");
	                    createCheckBox(oTr,311,"Perfect Bunches");
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createCheckBox(oTr,312,"Gnomes");
	                oTbody.appendChild(oTr);
	            oTable.appendChild(oTbody);
	                    oTr = document.createElement('tr');
	                    	oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"1");
	                        oTh.textContent = "Building Materials";
                        oTr.appendChild(oTh);
                       	createCheckBoxList(oTr,320,"Bricks,Nails,Wooden Boards,Horseshoes,Harnesses,Bottles,Blankets,Glass Sheets,Green Beams,Floral Brackets,White Trellises,Irrigation Pipes,Stable materials,Maison materials,Nursery materials,Garden materials,Garden decoration items,Maison decoration items");
	                oTbody.appendChild(oTr);
   	            oTable.appendChild(oTbody);
   	                    oTr = document.createElement('tr');
	                    	oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"1");
	                        oTh.textContent = "Bushels";
                        oTr.appendChild(oTh);
                       	createCheckBoxList(oTr,340,"Acorn Squash,Aloe Vera,Artichoke,Asparagus,Bell Pepper,Blackberry,Blueberry,Broccoli,Cabbage,Carrot,Coffee,Corn,Cotton,Cranberry,Cucumber,Daffodil,Eggplant,Ghost Chili,Ginger,Grape,Green Tea,IrisBasil,Lavender,Lilac,Lily,Morning Glory,Onion,Pattypan Squash,Pea,Peanut,Peas,Pepper,Pineapple,Pink Rose,Potato,Pumpkin,Purple Poppy,Raspberry,Red Tulip,Red Wheat,Rice,Soybean,Squash,Strawberry,Sugar Cane,Sunflower,Tomato,Watermelon,Wheat,White Grape,Yellow Melon,Unknown");
	                oTbody.appendChild(oTr);
   	            oTable.appendChild(oTbody);
   	                    oTr = document.createElement('tr');
	                    	oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"1");
	                        oTh.textContent = "Hatch ";
                        oTr.appendChild(oTh);
                       	createCheckBoxList(oTr,340,"White Eggs,Brown Eggs,Black Eggs,Gold Eggs,Rhode Island Red Eggs,Scots Grey Eggs,Cornish Eggs,Unknown");
	                oTbody.appendChild(oTr);
   	            oTable.appendChild(oTbody);
   	                    oTr = document.createElement('tr');
	                    	oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"1");
	                        oTh.textContent = "Adopt an Animal";
                        oTr.appendChild(oTh);
                       	createCheckBoxList(oTr,360,"White Cow,Brown Cow,Pink Cow,Fan Cow,Purple Cow,Chocolate Cow,Groovy Cow,White Calf,Green Calf,Kelly Green Calf,Pink Calf,Purple Calf,Pink Patch Calf,Brown Calf,Chocolate Calf,Fan Calf,Longhorn Calf,Tuscan Calf,Neapolitan Calf,Holstein Calf,Groovy Calf,Belted Calf,Brown Foal,White Foal,Grey Foal,Black Foal,Black Stallion Foal,Percheron Foal,Pinto Foal,Clydesdale Foal,Cream Clydesdale Foal,Pony Foal,Pink Pony Foal,Purple Pony Foal,Blue Pony Foal,Appaloosa Foal,Mustang Foal,Haflinger Foal,Penguins,Bulls,Turtles,Turkey,White Sheep,Black Sheep,Mouflon Sheep,White Kittens,Black Kittens,Ugly Ducklings,Rabbits,Reindeer,Grey Horse,Black Stallion,Boer Goat,Mouflon Goat,Llama,Unknown");
	                oTbody.appendChild(oTr);
   	            oTable.appendChild(oTbody);
   	            
            oForm.appendChild(oTable);
        oDom.appendChild(oForm);
        return oDom;
    };

    function CreateOtherTab(_id) {
        var oDom, oForm, oTable, oTbody, oTr, oTh, oTd ;
        oDom = document.createElement('div');
        if (_id==0)
            oDom.setAttribute('style','display: ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;')
        else
            oDom.setAttribute('style','display:none ;border: 1px solid rgb(204, 204, 204); overflow: auto; background-color: white; width: 480px; height: 280px;');

        oDom.id = strFBAASetDivs+_id;
			oForm = document.createElement('form');
	            oForm.name = 'FBAA-Form'+_id;
	
	            // create layout;
	            oTable = document.createElement('table');
	            oTable.setAttribute('width','100%');
	                oTbody = document.createElement('tbody');
	                    oTr = document.createElement('tr');
	                        oTh = document.createElement('th');
	                        oTh.setAttribute('style',"");
	                        oTh.setAttribute('colspan',"4");
	                        oTh.textContent = "Request Settings";
	                    oTr.appendChild(oTh);
	                oTbody.appendChild(oTr);
	                    oTr = document.createElement('tr');
	                    createDropDownList(oTr, 400,'Everyting','Ignore;Do Nothing','1;0');
	                oTbody.appendChild(oTr);
	            oTable.appendChild(oTbody);

            oForm.appendChild(oTable);
        oDom.appendChild(oForm);
        return oDom;
    };

}

function LogPush(_strTemp) {
    var oDiv;

    oDiv = document.createElement('div');
    oDiv.setAttribute('style','padding-bottom: 4px');
    oDiv.innerHTML = getCalendarDate()+', '+getClockTime()+': '+_strTemp;

    oLogDiv.insertBefore(oDiv,oLogDiv.firstChild);

    while (oLogDiv.childNodes.length>aParams[4]) {
        //GM_log('removing node');
        oLogDiv.removeChild(oLogDiv.lastChild);
    }

    GM_setValue('LogDiv',oLogDiv.innerHTML);
}

/**** Main Loop ****/

function MainLoop(){

    if (!bInitialized) {
        if (document.getElementById('login_form')==null) {

            // start things up once they are logged into facebook;
            bInitialized = true;
            Initialize();
        }
    } else {
        if (document.getElementById('login_form')!=null) {
            // they've logged out of facebook
            StopProcessing();
            bInitialized = false;
        } else if (document.getElementById('contentCol') != null ) {
            createDisplay();
        } else {
            GM_log('Ignore this Window');
        }
    }
};

/**** DOM Notify and Change Code ****/

function notifyChange() {
    if (notify_count == change_count) MainLoop();
    if (notify_count != change_count) {
        schedNotify();
        return;
    }
    scheduled = false;
};

function schedNotify() {
    scheduled = true;
    notify_count = change_count;
    iOnloadEvent = setTimeout(function (e) {
        notifyChange();
    },
    250);
};


/**** Start Main Code ****/

// FB and MW Detection
// We are only worried about the URL detection because of the excludes

try {
	// we only want the script running on the top window
	GM_log('top.location.href = '+ top.location.href);
	if (self.location.href.indexOf('www.facebook.com')!=-1) {
	    strFrameId  = 'FaceBook';
	} else {
	    strFrameId  = 'MafiaWars';
	}
	
	bInitialized = false;
	
	// add event listners for load and unload
	
	if ( strFrameId == "FaceBook") {
	    
        document.addEventListener("DOMNodeInserted", function (e) {
            change_count++;
            if (!scheduled && change_count > 2 ) schedNotify();
        },
        false);
	    
	    window.addEventListener("unload", function (e) {
	        try {
	            bAutoRun = false;
			    clearTimeout(iRespectCurrent);
	    		clearTimeout(iRequestCurrent);
	    		clearTimeout(iWallCurrent);
	            clearTimeout(iMW_XW_Timer);
	            clearTimeout(iFB_XW_Timer);
	            GM_log('Scripts are unloading.  Frame = '+strFrameId);
	        } catch(_errObj) {
	            GM_log('Something bad has happend - '+_errObj.message);
	        }
	    },
	    false);
	} else {
	
	    // for MW window when it opens
	
	    Initialize();
	}
} catch (_errObj) {
	GM_log('Exiting.  Script only runs on the top window');
}

/****  xw_sig Update Routines  ****/

function MW_xw_sig_update() {

    var iHoldEvent
    var oDiv,i1,i2

    iHoldEvent = iMW_XW_Timer;

    // if MW is open extract the current XW_SIG, and save it and the time.
    if (unsafeWindow.local_xw_sig != undefined) {
        // read the local_sw_sig value and save it
        GM_setValue('local_xw_sig', unsafeWindow.local_xw_sig);
        GM_setValue('local_xw_time',getCurrentTime());

        // Extract 'sf_xw_user_id' at the same time
        oDiv = document.getElementById('verytop');
        i1 = oDiv.innerHTML.indexOf('sf_xw_user_id=');
        if (i1!=-1) {
            i2 = oDiv.innerHTML.indexOf('&',i1);
            local_xw_user_id = oDiv.innerHTML.slice(i1+14,i2)
            GM_setValue('local_xw_user_id', local_xw_user_id);
        }

        GM_log('Saving local_xw_sig, local_xw_user_id, and local_xw_time from MW tab');

        // run every 5 minutes
        iMW_XW_Timer = setTimeout(function (e) { MW_xw_sig_update(); },300000);
        if (iMW_XW_Timer < iHoldEvent ) clearTimeout(iMW_XW_Timer);

    }




}

function FB_xw_sig_update() {

    var iHoldEvent, myUrl;

    iHoldEvent = iFB_XW_Timer;

    // this will keep the xw_sig_uptodate

    local_xw_sig        =   GM_getValue('local_xw_sig');
    local_xw_user_id    =   GM_getValue('local_xw_user_id','');
    local_xw_time       =   GM_getValue('local_xw_time',0);

    // check the age of the xw_sig
    if (((getCurrentTime()-local_xw_time) > 10) || (local_xw_user_id=='')) {

        myUrl = 'http://apps.facebook.com/inthemafia/?zy_link=appage';
        LogPush('<strong>Mafia Wars credential are out of date.  Attempting to refresh</strong>');

        GM_xmlhttpRequest({
            method: 'GET',
            url:  myUrl,
            headers: {
                'Host':            'apps.facebook.com',
                'User-agent':       navigator.userAgent,
                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-us,en;q=0.5',
                'Accept-Encoding': 'gzip,deflate',
                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
            },
            onload: function(_responseDetails) {

                var i1, i2, strTemp, myUrl;

                if (_responseDetails.status == 200) {
                    strTemp = _responseDetails.responseText;

                    i1=0;
                    myUrl = '';

                    do {
                        i1 = strTemp.indexOf('<iframe',i1);
                        if (i1 == -1) {
                            break;
                        } else {
                            i1 = strTemp.indexOf('src="',i1);
                            i2 = strTemp.indexOf('"',i1+5);
                            myUrl = strTemp.slice(i1+5,i2);
                            myUrl = myUrl.replace(/&amp;/g,'&');

                            if (myUrl.match(/facebook.mafiawars.com/i) == null) {
                                myUrl = '';
                            } else {
                                break;
                            }
                        }
                    } while (true)


                    if (myUrl != '') {

                        GM_xmlhttpRequest({

                            method: 'HEAD',
                            url:  myUrl,
                            headers: {
                                'Host':            'facebook.mafiawars.com',
                                'User-agent':       navigator.userAgent,
                                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                                'Accept-Language': 'en-us,en;q=0.5',
                                'Accept-Encoding': 'gzip,deflate',
                                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
                            },
                            onload: function(_responseDetails) {
                                var i1, i2, strTemp, myUrl;

                                if (_responseDetails.status == 200) {

                                    strTemp = _responseDetails.responseText;
                                    i1 = strTemp.indexOf("var local_xw_sig = '");
                                    if (i1 !=-1) {
                                        i2 = strTemp.indexOf("';",i1);
                                        local_xw_sig        = strTemp.slice(i1+20,i2);
                                        local_xw_time       = getCurrentTime();
                                        xw_sig_valid        = true;

                                        // Extract 'sf_xw_user_id' at the same time

                                        i1 = strTemp.indexOf('sf_xw_user_id=');
                                        if (i1!=-1) {
                                            i2 = strTemp.indexOf('&',i1);
                                            local_xw_user_id = strTemp.slice(i1+14,i2)
                                        }


                                        GM_setValue('local_xw_sig',local_xw_sig);
                                        GM_setValue('local_xw_user_id', local_xw_user_id);
                                        GM_setValue('local_xw_time',local_xw_time);

                                        GM_log('local_xw_sig = '+local_xw_sig+', local_xw_user_id = '+local_xw_user_id+', local_xw_time = '+local_xw_time);

                                        LogPush('Mafia Wars crentials have been sucessfully renewed');

                                        iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 300000);
                                        if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);

                                        // check Languague

                                        checkLanguage(strTemp)

                                    } else {
                                        GM_log('Mafia War does not appear to be working');
                                        LogPush('Cannot Update Mafia Wars credentials.  Mafia Wars may be down<br>Attempting again in 5 minutes');
                                        xw_sig_valid        = false;
                                        local_xw_time       = 0;
                                        GM_setValue('local_xw_time',local_xw_time);

                                        iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 300000);
                                        if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                                    }
                                } else {
                                    GM_log('Error loading FB/Mafia Wars Page');
                                    LogPush('Cannot Update Mafia Wars credentials<br>Attempting again in 5 minutes');
                                    xw_sig_valid        = false;
                                    local_xw_time       = 0;
                                    GM_setValue('local_xw_time',local_xw_time);

                                    iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 300000);
                                    if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                                }
                            }
                        });

                    } else {
                        GM_log('Cannot find Mafia Wars iFrame');
                        LogPush('Cannot Update Mafia Wars credentials<br>Attempting again in 5 minutes');
                        xw_sig_valid        = false;
                        local_xw_time       = 0;
                        GM_setValue('local_xw_time',local_xw_time);

                        iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 300000);
                        if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                    }
                } else {
                    GM_log('Error loading FB/Mafia Wars Page');
                    LogPush('Cannot Update Mafia Wars credentials<br>Attempting again in 5 minutes');
                    xw_sig_valid        = false;
                    local_xw_time       = 0;
                    GM_setValue('local_xw_time',local_xw_time);

                    iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 300000);
                    if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                }
            }
        });

    } else {

        GM_xmlhttpRequest({

            method: 'POST',
            url:  'http://facebook.mafiawars.com/mwfb/sf_updater.php ',
            data: 'sf_xw_user_id='+local_xw_user_id+'&sf_xw_sig='+local_xw_sig+'&skip_req_frame=1',
            headers: {
                'Host':            'facebook.mafiawars.com',
                'User-agent':       navigator.userAgent,
                'Content-Type':    'application/x-www-form-urlencoded',
                'Accept':          '*/*',
                'Accept-Language': 'en-us,en;q=0.5',
                'Accept-Encoding': 'gzip,deflate',
                'Accept-Charset':  'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
                'X-Requested-With':'XMLHttpRequest'
            },
            onload: function(_responseDetails) {

                var strTemp;
                var i1, i2;
                strTemp = _responseDetails.responseText;

                if (_responseDetails.status == 200) {
                    if (strTemp.indexOf('local_xw_sig') != -1) {
                        i1 = strTemp.indexOf('local_xw_sig')
                        i2 = strTemp.indexOf("';",i1)
                        local_xw_sig        = strTemp.slice(i1+16,i2);
                        local_xw_time       = getCurrentTime();
                        xw_sig_valid = true;

                        GM_setValue('local_xw_sig',local_xw_sig);
                        GM_setValue('local_xw_time',local_xw_time);

                        GM_log('local_xw_sig = '+local_xw_sig+', local_xw_time = '+local_xw_time);

                        //repeat every 3 minutes
                        iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 180000);
                        if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                    } else {
                        xw_sig_valid        = false;
                        local_xw_time       = 0;
                        GM_setValue('local_xw_time',local_xw_time);

                        GM_log('Error renewing XW_SIG');

                        iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 1000);
                        if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                    }

                } else {
                    xw_sig_valid        = false;
                    local_xw_time       = 0;
                    GM_setValue('local_xw_time',local_xw_time);

                    GM_log('Error renewing XW_SIG');
                    iFB_XW_Timer = setTimeout(function (e) { FB_xw_sig_update(); }, 1000);
                    if (iFB_XW_Timer < iHoldEvent ) clearTimeout(iFB_XW_Timer);
                }
            }
        });
    }
}

/**** Utility functions ****/

// gets the current timestamp in minutes
function getCurrentTime() {
    return Math.round(new Date().getTime() / 1000 / 60);
}

// gets a random num within a range
function getRandRange(_iLow, _iHigh) {
    return Math.floor((_iHigh - _iLow) * Math.random()) + _iLow;
}

// get a Snapshot based on an XPath
function getSnapshot(_strPattern,_doc) {
    // default is document if _doc is not provided
    return document.evaluate(_strPattern, (_doc===undefined?document:_doc), null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
}

// remove special characters from strings
function codeStrings(_str) {
	
	var strTemp = _str;
	strTemp= strTemp.replace(/\s/g, '%20');
	strTemp= strTemp.replace(/:/g,  '%3A');
	strTemp= strTemp.replace(/\//g, '%2F');
	strTemp= strTemp.replace(/\?/g,  '%3F');
	strTemp= strTemp.replace(/=/g,  '%3D');
	strTemp= strTemp.replace(/&/g,  '%26');
	strTemp= strTemp.replace(/,/g,  '%2C');
	
    return strTemp;
}

function codeStrings2(_str) {
	
	var strTemp = _str;
	
	strTemp= strTemp.replace(/\s/g, '%20');
	strTemp= strTemp.replace(/:/g,  '%3A');
	strTemp= strTemp.replace(/\//g, '%2F');
	strTemp= strTemp.replace(/\?/g, '%3F');
	strTemp= strTemp.replace(/=/g,  '%3D');
	strTemp= strTemp.replace(/&/g,  '%26');
	strTemp= strTemp.replace(/,/g,  '%2C');
    strTemp= strTemp.replace(/{/g,  '%7B');
    strTemp= strTemp.replace(/}/g,  '%7D');
    strTemp= strTemp.replace(/"/g,  '%22');
    strTemp= strTemp.replace(/%/g,  '%25');
    strTemp= strTemp.replace(/$/g,  '%24');
    strTemp= strTemp.replace(/\(/g, '%28');
    strTemp= strTemp.replace(/\)/g, '%29');
    strTemp= strTemp.replace(/!/g,  '%21');
    
    return strTemp;
}

function decodeStrings(_str) {

    var strTemp = _str;
    strTemp= strTemp.replace(/%20/g,  ' ');
    strTemp= strTemp.replace(/%22/g,  '"');
    strTemp= strTemp.replace(/%25/g,  '%');
    strTemp= strTemp.replace(/%26/g,  '&');
    strTemp= strTemp.replace(/%2C/g,  ',');
    strTemp= strTemp.replace(/%2F/g,  '/');
    strTemp= strTemp.replace(/%3A/g,  ':');
    strTemp= strTemp.replace(/%3D/g,  '=');
    strTemp= strTemp.replace(/%3F/g,  '?');
    strTemp= strTemp.replace(/%5B/g,  '[');
    strTemp= strTemp.replace(/%5D/g,  ']');
    strTemp= strTemp.replace(/%7B/g,  '{');
    strTemp= strTemp.replace(/%7D/g,  '}');
    
    return strTemp;
}

function getCalendarDate() {
    var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    var now         = new Date();
    var monthnumber = now.getMonth();
    var monthname   = months[monthnumber];
    var monthday    = now.getDate();
    var year        = now.getYear();
    if(year < 2000) { year = year + 1900; }
    var dateString = monthname + ' ' +  monthday;
    return dateString;
}

function getClockTime() {
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour + ':' + minute + ':' + second + " " + ap;
   return timeString;
}

function requestName(_strTemp) {

    var i,j;

    j = 0;
    for (i=0;i<3;i++) j=_strTemp.indexOf(' ',j)+1;

    return _strTemp.slice(j,j+1).toUpperCase() +  _strTemp.slice(j+1);
}


function getGroupNames(){

    // we are looging to build this
    // &params[lists]=[%22100423413310424%3AMafia%20Wars%22]
    // "100423413310424=Mafia Wars"

    strGroups       =   '<option value="0">-</option>';

    GM_xmlhttpRequest({
        url:"http://www.facebook.com/friends/?ref=tn",
        method:'get',
        onload: function(resp){
            var i1, i2, i3, i4;
            var strTemp, strDiv, strId, strName;

            strTemp = resp.responseText;
            i1 = 0;
            do {
                i1 = strTemp.indexOf('<div class="UIFilterList_Item', i1);
                if (i1!= -1) {
                    i2 = strTemp.indexOf('<div class="UIFilterList_Item',i1+1);
                    if (i2==-1) i2 = strTemp.indexOf('</span',i1+1);
                    strDiv = strTemp.slice(i1,i2);
                    i3 = strDiv.indexOf('filter=flp_');
                    if ( i3 != -1) {
                        i4 = strDiv.indexOf('"',i3+11);
                        strId = strDiv.slice(i3+11,i4);
                        i3 = strDiv.indexOf('title="');
                        i4 = strDiv.indexOf('"',i3+7);
                        strName = strDiv.slice(i3+7,i4);

                        strGroups       +=  '<option value="';
                        strGroups       +=  '%22'+codeStrings(strId+'='+strName)+'%22';
                        strGroups       +=  '">'+strName+'</option>';
                    }
                    i1=i2;
                }
            } while (i1 != -1)

            // try to update display
            oForm = document.forms.namedItem('FBAA-Form1');
            if (oForm != null) {
                oForm.elements.namedItem('FBAA-Para-101').innerHTML = strGroups;
                oForm.elements.namedItem('FBAA-Para-101').value = aParams[101];
                oForm.elements.namedItem('FBAA-Para-103').innerHTML = strGroups;
                oForm.elements.namedItem('FBAA-Para-103').value = aParams[103];


            }
        }
    });
}

function checkLanguage(_strHTML) {

    var i1, i2;
    var strLang;
    var re;

    //<input type=hidden name ="mw_locale" id="mw_locale" value="en_US">
    //Valid choices are  de_DE, en_US, es_ES, es_MX, fr_FR, id_ID.

    re = /de_DE|en_US|es_ES|es_MX|fr_FR|id_ID/i


    strLang = GM_getValue('Language','en_US');

    i1  =   _strHTML.indexOf('id="mw_locale"');
    GM_setValue('Language',strLang);

    if (i1!=-1) {
        i1      =   _strHTML.indexOf('value="',i1) + 7 ;
        i2      =   _strHTML.indexOf('"',i1);
        strLang =   _strHTML.slice(i1,i2);

        if (!re.test(strLang)) {
            GM_log('Language Check Error - fixing');
            if(strLang=="") strLang = "en_US"
            else if(strLang.indexOf('de_')) strLang = "de_DE"
            else if(strLang.indexOf('en_')) strLang = "en_US"
            else if(strLang.indexOf('es_')) strLang = "en_ES"
            else if(strLang.indexOf('fr_')) strLang = "en_FR"
            else if(strLang.indexOf('id_')) strLang = "en_ID"
            else strLang = "en_US";
        }
        GM_setValue('Language',strLang);
    } else {
        GM_log('Error Language check');
    }

    return strLang;
}


/****  Listner ****/

function click_AutoRun(iButton) {
    return function () {
        var oSpan;

        GM_log('the following button was pushed ' + iButton);

        if (iButton == 1) {
            document.getElementById(strAutoOn).innerHTML= '<b>On</b>';
            document.getElementById(strAutoOff).innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Off</a> </font>';

            if (!bAutoRun){
                bAutoRun = true;
                GM_setValue('bAutoRun',bAutoRun);
                StartProcessing();
            }

        } else {
            document.getElementById(strAutoOff).innerHTML= '<b>Off</b>';
            document.getElementById(strAutoOn).innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>On</a> </font>';
            bAutoRun = false;
            GM_setValue('bAutoRun',bAutoRun);
            StopProcessing();

        }

        // do something to start or stop the processing of requests.

    }
}

function click_ShowSettingsTab(iButton) {
    return function () {

        var oLi, oDiv;

        for (var i=0;i<5;i++) {
            oLi = document.getElementById(strFBAASetTabs+i);
            oDiv = document.getElementById(strFBAASetDivs+i);
            if (i==iButton) {
                oLi.setAttribute('class','selected');
                oDiv.style.display = "";
            } else {
                oLi.setAttribute('class','');
                oDiv.style.display = "none";
            }
        }
    }
}

function click_CloseSettings(iButton) {
    return function () {
        var oForm, oItem;
        var oDiv, strTemp;

        if (iButton == 0) {

            for (var i=0;i<5;i++) {
                strTemp = '';
                oForm = document.forms.namedItem('FBAA-Form'+i);
                for (var j=0; j<oForm.length; j++) {
                    if (j>0) strTemp +=';';
                    oItem = oForm.elements.namedItem('FBAA-Para-'+(i*100+j));
                    if (oItem != undefined ) {
                        if (oItem.type == 'checkbox') {
                            strTemp             += oItem.checked;
                            aParams[i*100+j]     = oItem.checked;
                        } else {
                            strTemp             += oItem.value+'';
                            aParams[i*100+j]     = oItem.value;
                        }
                    }
                }

                GM_log('FBAA-Form'+i+' = '+strTemp);
                GM_setValue('FBAA-Form'+i,strTemp);
            }
            oDiv = document.getElementById(strFBAASettings);
            oDiv.style.display="none";
        } else {
            oDiv = document.getElementById(strFBAASettings);
            oDiv.style.display="none";
        }
        if (bAutoRunHold){
            StartProcessing();
        }
    }
}


function click_ShowLog(iButton) {
    return function () {
        var iBC, oButtons, oButton, iButtons, ODOM;
        var oSpan;

        GM_log('the following button was pushed ' + iButton);

        if (iButton == 1) {
            document.getElementById(strLogShow).innerHTML= '<b>Show</b>';
            document.getElementById(strLogHide).innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Hide</a> </font>';
            bShowLog = true;
            GM_setValue('bShowLog',bShowLog);
            oLogDiv.parentNode.style.display = ""
        } else {
            document.getElementById(strLogHide).innerHTML= '<b>Hide</b>';
            document.getElementById(strLogShow).innerHTML= '<font style="color: rgb(59, 89, 152); cursor: pointer;"> <a>Show</a> </font>';
            bShowLog = false;
            GM_setValue('bShowLog',bShowLog);
            oLogDiv.parentNode.style.display = "none"
        }
    }
}

function click_ClearLog() {
    oLogDiv.innerHTML = "";

    GM_setValue('LogDiv',oLogDiv.innerHTML);

}

function click_ShowSetting() {
    var oDiv;
    var oForm, oItem;

    bAutoRunHold = bAutoRun;

    //stop processing
    if (bAutoRun) StopProcessing();

    // get Names
    getGroupNames()

    // put in group Names
    oForm = document.forms.namedItem('FBAA-Form1');
    oForm.elements.namedItem('FBAA-Para-101').innerHTML = strGroups;
    oForm.elements.namedItem('FBAA-Para-103').innerHTML = strGroups;
    GM_log(oForm.elements.namedItem('FBAA-Para-101').innerHTML);

    // plug in saved values;
    for (var i=0;i<5;i++) {
        oForm = document.forms.namedItem('FBAA-Form'+i);
        for (var j=0; j<oForm.length; j++) {
            GM_log(j +' '+ oForm.length);
            oItem = oForm.elements.namedItem('FBAA-Para-'+(i*100+j));
            if (oItem != undefined) {
                GM_log('oItem.type' + oItem.type );
                if (oItem.type == 'checkbox')
                    oItem.checked   = aParams[i*100+j]
                else
                    oItem.value     = aParams[i*100+j];
            }
        }
     }

    oDiv = document.getElementById(strFBAASettings);
    oDiv.style.display="";

}

// Script Update Update Code

function updateCheck(forced) {
    // Checks once a day (24 h * 60 m * 60 s * 1000 ms) unless forced
    if ((forced) || (parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime()))) {
        try {
            //read the script page on the USERSCRIPT.ORG web page
            GM_xmlhttpRequest( {
                method: 'GET',
                url: 'http://userscripts.org/scripts/source/'+SUC_script_num+'.meta.js?'+new Date().getTime(),
                headers: {'Cache-Control': 'no-cache'},
                onload: function(resp) {

                    var local_version, remote_version, rt, script_name;

                    rt = resp.responseText;

                    //set the time of the last successful update
                    GM_setValue('SUC_last_update', new Date().getTime()+'');

                    //get the remote version number and save the scripts name
                    remote_version=parseInt(/@uso:version\s*(.*?)\s*$/m.exec(rt)[1]);
                    script_name = (/@name\s*(.*?)\s*$/m.exec(rt))[1];

                    //get the local version number
                    local_version=parseInt(GM_getValue('SUC_current_version', '-1'));

                    if(local_version!=-1) {
                        // test to see if a new version is available

                        if (remote_version > local_version) {
                            if(confirm('There is an update available for the Greasemonkey script "'+script_name+'."\nWould you like to go to the install page now?')) {
                                try {
                                    window.location.href = 'http://userscripts.org/scripts/source/'+SUC_script_num+'.user.js';
                                } catch (err) {
                                };
                                GM_setValue('SUC_current_version', remote_version);
                            }
                        } else if (forced) {
                            alert('No update is available for "'+script_name+'."');
                        }
                    } else {
                        // if the script has never run save the version numnber
                        GM_setValue('SUC_target_script_name', script_name+'');
                        GM_setValue('SUC_current_version', remote_version+'');
                    }
                }
            });
        } catch (err) {
            if (forced)
                alert('An error occurred while checking for updates:\n'+err);
        }
    }
}

function SendEncode(_strTemp) {

    var strTemp1;

    strTemp1='';

    for (i=0; i<_strTemp.length; i++) {
        iTest = _strTemp.charCodeAt(i)
        if (iTest == 45 ) {
            strTemp1 += '-';
        } else if (iTest == 32 ) {
            strTemp1 += '+';
        } else if (iTest < 48) {
            strTemp1 += '%' +('000'+iTest.toString(16)).slice(-2);
        } else if (iTest>57 && iTest<65) {
            strTemp1 += '%' +('000'+iTest.toString(16)).slice(-2);
        } else if (iTest>90 && iTest<97) {
            strTemp1 += '%' +('000'+iTest.toString(16)).slice(-2);
        } else if (iTest>122 && iTest<127) {
            strTemp1 += '%' +('000'+iTest.toString(16)).slice(-2);
        } else {
            strTemp1 += _strTemp[i];
        }
    }

    return strTemp1;
}